How to return indices of values โ€‹โ€‹between two numbers in a numpy array

I would like to return the indices of all the values โ€‹โ€‹in a numpy python 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 would like to know if there is a way to do this without iterating through an array. Thanks!

+6
source share
2 answers

Since > < = returns masked arrays, you can propagate them together to get the effect you are looking for (essentially a 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]) 
+11
source

You can combine multiple boolean expressions with parentheses and work correctly:

 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 for a variable to extract the values:

 In [4]: idx = np.where((A > 2) & (A < 8)) In [5]: A[idx] Out[5]: array([4, 6]) 
+4
source

Source: https://habr.com/ru/post/977847/


All Articles