Creating a boolean array by testing if each element in numpy array is between 2 numbers

五迷三道 提交于 2021-02-17 05:46:25

问题


I have a numpy array of numbers and i want to create a boolean array of the same size and dimensions that says whether or not that element lies between 2 numbers. For example:

a=np.array([[1,2,3],[4,5,6],[7,8,9]])

I know if I write,

print a>3

I get an array that has the first three elements "False" and the rest "True"

np.array([[False,False,False],[True,True,True],[True,True,True]])

But i want to get a boolean array where the conditions are such that

a>3 and a<8

Is there a way to do this without checking every element one by one in a for loop? I have arrays that are 2048*2048 and that takes too long

Some has reported that is is the same question as another where the solution was to use the numpy.where function, but that returns the elements where a condition is true, my question is to return booleans


回答1:


You can check for a range like this:

print (3<a)&(a<8)


来源:https://stackoverflow.com/questions/33356461/creating-a-boolean-array-by-testing-if-each-element-in-numpy-array-is-between-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!