0

I know that in Numpy you can mask an array based on a condition. For example, if I want a masked array for all values greater than 0.

arr[arr>0]

But I want to have two conditions for the mask. Intuitively, this would look like:

arr[arr>0 and arr<1]

but the compiler pops an error:

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

I know I can use a for loop to solve this:

masked=np.array([i if(i>0 and i<1) for i in mask])

but is there a more elegant solution using something that's built-in for Numpy?

playerJX1
  • 209
  • 1
  • 11

1 Answers1

1

You want this:

arr[(arr > 0) & (arr < 1)]
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • thanks, I should have tried that. Is there an explanation as to why "and" doesn't work? – playerJX1 Jul 01 '23 at 10:00
  • 1
    "and" expects to produce a scalar True/False. You want elementwise logic. – John Zwinck Jul 01 '23 at 10:01
  • Interesting, now that you mentioned it I found a page that explains this in a similar scenario: https://stackoverflow.com/questions/8632033/how-to-perform-element-wise-boolean-operations-on-numpy-arrays. – playerJX1 Jul 01 '23 at 10:05
  • `and` is a Python expression, more like a `if/else` clause than an operator. `True and 1` returns `1`, more like `1 if True else False`. (except it short circuits) – hpaulj Jul 01 '23 at 18:01