Search code examples
pythonnumpy

How do I use np.where with multiple conditions


How do I specify more than one condition when using np.where() to get the indices of the elements of an array that fulfill all of those conditions?

a = np.array([1, 2, 3, 4, 5, 6]) 
print(np.where(a > 2 and a < 5))

When I say

print(np.where(a > 2))

I get the indices [2, 3, 4, 5] but now I want to just get [2, 3].


Solution

  • You have to use bitwise operators, & for and, | for or, and so on.

    With your example,

    a = np.array([1, 2, 3, 4, 5, 6])
    np.where((a > 2) & (a < 5))
    

    returns

    (array([2, 3], dtype=int64),)