Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find elements within range in numpy in Python
Sometimes 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.
Using logical_and() with where()
In this approach we take a 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)
The output of the above code is ?
Given Array : [ 5 9 11 4 31 27 8] Array with condition : (array([1, 2, 6]),)
Using Boolean Indexing with * Operator
In this approach we use the * operator for boolean indexing. 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)
The output of the above code is ?
Given Array : [ 5 9 11 4 31 27 8] Array with condition : [ 9 11 8]
Using & Operator (Recommended)
The most pythonic way is using the & operator with parentheses for boolean indexing ?
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 using & operator
res = A[(A >= 6) & (A <= 15)]
# Result
print("Array with condition : ", res)
The output of the above code is ?
Given Array : [ 5 9 11 4 31 27 8] Array with condition : [ 9 11 8]
Comparison
| Method | Returns | Best For |
|---|---|---|
np.where() with logical_and() |
Indices | When you need positions |
* operator |
Values | Boolean indexing |
& operator |
Values | Most readable and pythonic |
Conclusion
Use np.where() with logical_and() when you need indices of elements within a range. For filtering values, the & operator with boolean indexing is the most readable and recommended approach.
