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!
Explanation. In line 1, we import the numpy package. In line 4, we create an array and specify the number of elements to be 10 , ranging from 1 to 10. In line 7, we use the logical_and() method and specify two conditions to extract the elements, which are greater than or equal to 7 and less than 11.
The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.
In this article, we are going to find the index of the elements present in a Numpy array using where() method. It is used to specify the index of a particular element specified in the condition.
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With