I have a numpy array of numbers, for example,
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
I would like to find all the indexes of the elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.
Using the logical_and() method The logical_and() method from the numpy package accepts multiple conditions or expressions as a parameter. Each of the conditions or the expressions should return a boolean value. These boolean values are used to extract the required elements from the array.
You can use np.where
to get indices and np.logical_and
to set two conditions:
import numpy as np a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56]) np.where(np.logical_and(a>=6, a<=10)) # returns (array([3, 4, 5]),)
As in @deinonychusaur's reply, but even more compact:
In [7]: np.where((a >= 6) & (a <=10)) Out[7]: (array([3, 4, 5]),)
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