-1

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?

Izzy
  • 179
  • 1
  • 13
  • Why does `np.where(arr >= A and arr <= B)`, which was the first thing I tried, fail? – Izzy May 10 '22 at 17:41
  • 1
    Python doesn't allow overloading `and` and `or`: https://stackoverflow.com/q/32311518. See the warnings in the numpy docs: https://numpy.org/doc/stable/reference/ufuncs.html#comparison-functions – yut23 May 10 '22 at 17:58

1 Answers1

2

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)
AlexM4
  • 503
  • 5
  • 12