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
Selected Reading
How to print array elements within a given range using Numpy?
In NumPy, you can print array elements within a specific range using several methods. The most common approaches are numpy.where() with numpy.logical_and(), boolean indexing, and conditional filtering.
Using numpy.where() with logical_and()
The numpy.where() function returns the indices of elements that meet a condition ?
import numpy as np
arr = np.array([1, 3, 5, 7, 10, 2, 4, 6, 8, 10, 36])
print("Original Array:")
print(arr)
# Find indices of elements between 4 and 20 (inclusive)
indices = np.where(np.logical_and(arr >= 4, arr <= 20))
print("\nIndices of elements in range [4, 20]:")
print(indices[0])
# Get the actual elements using the indices
elements_in_range = arr[indices]
print("\nElements in range [4, 20]:")
print(elements_in_range)
Original Array: [ 1 3 5 7 10 2 4 6 8 10 36] Indices of elements in range [4, 20]: [2 3 4 6 7 8 9] Elements in range [4, 20]: [ 5 7 10 4 6 8 10]
Using Boolean Indexing
Boolean indexing provides a more direct way to filter elements ?
import numpy as np
arr = np.array([1, 3, 5, 7, 10, 2, 4, 6, 8, 10, 36])
print("Original Array:")
print(arr)
# Create boolean mask for elements in range [4, 20]
mask = (arr >= 4) & (arr <= 20)
print("\nBoolean mask:")
print(mask)
# Extract elements using the mask
filtered_elements = arr[mask]
print("\nElements in range [4, 20]:")
print(filtered_elements)
Original Array: [ 1 3 5 7 10 2 4 6 8 10 36] Boolean mask: [False False True True True False True True True True False] Elements in range [4, 20]: [ 5 7 10 4 6 8 10]
Using numpy.extract()
The numpy.extract() function provides another approach for conditional filtering ?
import numpy as np
arr = np.array([1, 3, 5, 7, 10, 2, 4, 6, 8, 10, 36])
print("Original Array:")
print(arr)
# Extract elements in range [4, 20]
condition = (arr >= 4) & (arr <= 20)
filtered_elements = np.extract(condition, arr)
print("\nElements in range [4, 20]:")
print(filtered_elements)
Original Array: [ 1 3 5 7 10 2 4 6 8 10 36] Elements in range [4, 20]: [ 5 7 10 4 6 8 10]
Comparison of Methods
| Method | Returns | Best For |
|---|---|---|
np.where() |
Indices only | When you need index positions |
| Boolean indexing | Filtered elements | Most readable and efficient |
np.extract() |
Filtered elements | Functional programming style |
Conclusion
Boolean indexing with (arr >= min_val) & (arr is the most efficient and readable method. Use np.where() when you need both indices and values.
Advertisements
