Home > front end >  Using numpy.where() to compare numbers in an array to an interval
Using numpy.where() to compare numbers in an array to an interval

Time:05-11

I have an array of numbers:

my_arr = np.array([n, n 1, n 2 ... , m-1, m]

I want to create an array of Booleans which indicate which numbers are in some (closed) interval, [A,B], to operate on some other related array that has the same shape. There are two cases:

Case 1: B >= m or A <= n

This case is trivial; the interval can be fully described with only one Boolean expression, and np.where() provides the solution to testing my array; e.g.:

my_boolean_arr = np.where(my_arr >= A)

or it's equivalent for B. This works.

Case 2: n <= A and m >= B

Here, I run into problems. I can no longer reduce my interval expression into a "single" Boolean expression. Python allows me to come close: the expression A < x < B will return a single (correct) Boolean. However,

my_boolean_arr = np.where(A <= my_arr <= B)

now fails:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So, Two questions. First, how do I make this work? Second, why does this fail?

CodePudding user response:

Operators "and" and "or" are not defined for numpy arrays. In your case, you can use np.logical_and instead:

my_boolean_arr = np.logical_and(my_arr>=A, my_arr<=B)

https://numpy.org/doc/stable/reference/generated/numpy.logical_and.html

Alternative way is to use operator &

my_boolean_arr = (my_arr>=A) & (my_arr<=B)
  • Related