18

I would like to return the indices of all the values in a python numpy array that are between two values. Here is my code:

inEllipseIndFar = np.argwhere(excessPathLen * 2 < ePL < excessPathLen * 3)

But it returns an error:

inEllipseIndFar  = np.argwhere((excessPathLen * 2 < ePL < excessPathLen * 3).all())
ValueError: The truth value of an array with more than one element is ambiguous. Use 
a.any() or a.all()

I'd like to know if there is a way of doing this without iterating through the array. Thanks!

2 Answers 2

28

Since > < = return masked arrays, you can multiply them together to get the effect you are looking for (essentially the logical AND):

>>> import numpy as np
>>> A = 2*np.arange(10)
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

>>> idx = (A>2)*(A<8)
>>> np.where(idx)
array([2, 3])
Sign up to request clarification or add additional context in comments.

Comments

14

You can combine multiple boolean expressions by using parentheses and the correct operation:

In [1]: import numpy as np

In [2]: A = 2*np.arange(10)

In [3]: np.where((A > 2) & (A < 8))
Out[3]: (array([2, 3]),)

You can also set the result of np.where to a variable to extract the values:

In [4]: idx = np.where((A > 2) & (A < 8))

In [5]: A[idx]
Out[5]: array([4, 6])

3 Comments

Out of curiosity, is there any difference between multiplication and logical conjunction for True/False arrays?
@Hooked - Not really, but I find the compound logical statements to be more readable
Old comments, but for future readers: I ran timing on both (logical and multiplication) and the difference appears negligible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.