2

I can get numpy.where() to work for one condition but not two conditions.

For one condition:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0  5  8 10 11 12] ## indices where a[i] = 1

For two conditions:

# condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I read up on a.any() and a.all() in this other SO post, but this doesn't work for my purpose since I want all indices that fit the condition rather than a single boolean value.

Is there a way to adapt this for two conditions?

  • This value error is produced when you use a boolean array in a scalar context like an `if`, or in this case Python's `and`. Use `&` instead. And control operator order with `()`. – hpaulj Jul 07 '17 at 05:56

1 Answers1

6

Use np.where((a > 1) & (a < 3))

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214