Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 839
Alex Avatar asked Jun 10 '26 23:06

Alex


1 Answers

You can check for a range like this:

print (3<a)&(a<8)
like image 146
emre. Avatar answered Jun 12 '26 23:06

emre.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!