+5 votes
in Programming Languages by (73.8k points)
How can I specify multiple conditions using and/or in the where() function of Numpy?

E.g.

a=np.array([12,14,16,18,7,8,45,23,34])

I want to find indices of numbers that are less than 20 but greater than 10 using the where() function.

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

If you want to use multiple conditions in the where() function of Numpy, you need to put those conditions inside the parentheses "()," and instead of using and/or, you need to use &/|.

& is AND

| is OR

Here is an example to show how to use multiple conditions in the Numpy where() function.

>>> import numpy as np
>>> a=np.array([12,14,16,18,7,8,45,23,34])
>>> a
array([12, 14, 16, 18,  7,  8, 45, 23, 34])
>>> np.where((a>10) & (a<20))
(array([0, 1, 2, 3]),)
>>> a[np.where((a>10) & (a<20))[0]]
array([12, 14, 16, 18])


...