45
votes

I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work:

numpy.where((my_array > a) and (my_array < b))

How should I fix this? Or is there a better way to do it?

Thanks!

1
have you tried logical operators like & instead of and? - RodericDay
Just substituting and with & doesn't work, but I just found that this works: numpy.where((my_array > a) & (my_array < b) == True) - rferdinand
@user1803782: Can you explain it what sense replacing and with & doesn't work? It's the standard way to solve this problem. - Mark Dickinson
I'm actually not sure why it gave an error the first time. Now it does work. My bad. But thanks. - rferdinand

1 Answers

73
votes

Here are two ways:

In [1]: my_array = arange(10)

In [2]: where((my_array > 3) & (my_array < 7))
Out[2]: (array([4, 5, 6]),)

In [3]: where(logical_and(my_array > 3, my_array < 7))
Out[3]: (array([4, 5, 6]),)

For the first (replacing and with &), be careful to add parentheses appropriately: & has higher precedence than the comparison operators. You can also use *, but I wouldn't recommend it: it's hacky and doesn't make for readable code.

In [4]: where((my_array > 3) * (my_array < 7))
Out[4]: (array([4, 5, 6]),)