Alex
Alex

Reputation: 195

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

Upvotes: 3

Views: 6946

Answers (1)

emre.
emre.

Reputation: 1296

You can check for a range like this:

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

Upvotes: 1

Related Questions