Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: find index of the elements within range

Tags:

python

numpy

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?

like image 815
Bob Avatar asked Dec 13 '12 21:12

Bob


People also ask

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

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.

How do you extract all numbers between a given range from a 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.


2 Answers

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]),) 
like image 50
deinonychusaur Avatar answered Sep 22 '22 02:09

deinonychusaur


As in @deinonychusaur's reply, but even more compact:

In [7]: np.where((a >= 6) & (a <=10)) Out[7]: (array([3, 4, 5]),) 
like image 23
tiago Avatar answered Sep 26 '22 02:09

tiago