Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return indices of values between two numbers in numpy array

Tags:

python

numpy

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!

like image 364
JBaczuk Avatar asked Nov 06 '14 18:11

JBaczuk


People also ask

How do you extract all numbers between a given range from a NumPy array?

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.

How do you return an index from an array in Python?

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.

How do you find the index of an element in an NP array?

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.

Do NumPy arrays have indices?

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.


2 Answers

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])
like image 185
JoshAdel Avatar answered Oct 15 '22 04:10

JoshAdel


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])
like image 35
Hooked Avatar answered Oct 15 '22 03:10

Hooked