Find elements within range in numpy in Python



Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy.

With and operator

In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions.

import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# printing initial array
print("Given Array : ", A)

# Range 6 to 15
res = np.where(np.logical_and(A >= 6, A <= 15))

# Result
print("Array with condition : ", res)

Output

Running the above code gives us the following result −

Given Array : [ 5 9 11 4 31 27 8]
Array with condition : (array([1, 2, 6], dtype=int32),)

Using *

In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array.

import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# printing initial array
print("Given Array : ", A)

# Range 6 to 15
res = A [ (A >=6) * (A <= 15)]

# Result
print("Array with condition : ", res)

Output

Running the above code gives us the following result −

Given Array : [ 5 9 11 4 31 27 8]
Array with condition : [ 9 11 8]

Advertisements