NUMPY Tutorial



NumPy ARRAY FILTERING


🔹 NumPy Array Filtering

Filtering in NumPy means selecting elements from an array that satisfy a given condition. This is done using boolean indexing or mask arrays, which makes filtering very fast and convenient.

✅ Filtering Using Boolean Indexing

Boolean indexing returns a new array containing only elements that satisfy the condition.

import numpy as np

arr = np.array([10, 15, 20, 25, 30, 35, 40])

# Filter elements greater than 20
filtered_arr = arr[arr > 20]
print("Elements greater than 20:", filtered_arr)
# Output: [25 30 35 40]

✅ Combining Multiple Conditions

Use logical operators & (and), | (or), and parentheses to combine conditions.

# Filter elements greater than 15 and less than 35
filtered_arr2 = arr[(arr > 15) & (arr < 35)]
print("Elements >15 and <35:", filtered_arr2)
# Output: [20 25 30]

✅ Filtering with np.where()

While np.where() returns indices or can select values conditionally, you can also use it to filter elements:

indices = np.where(arr > 25)
print("Indices where arr > 25:", indices)
# Output: (array([4, 5, 6]),)

filtered_arr3 = arr[indices]
print("Filtered elements using np.where:", filtered_arr3)
# Output: [30 35 40]

✅ Filtering in 2D Arrays

Boolean indexing works for multidimensional arrays too:

arr2d = np.array([[5, 10, 15],
                  [20, 25, 30],
                  [35, 40, 45]])

filtered_2d = arr2d[arr2d % 2 == 0]  # Select even numbers
print("Even numbers from 2D array:", filtered_2d)
# Output: [10 20 30 40]

✅ Filtering with Custom Functions

You can create custom filter functions with np.vectorize or use simple list comprehensions combined with NumPy arrays:

def is_multiple_of_3(x):
    return x % 3 == 0

vec_func = np.vectorize(is_multiple_of_3)
mask = vec_func(arr)
filtered_custom = arr[mask]
print("Elements that are multiples of 3:", filtered_custom)
# Output: [15 30]

✅ Important Notes

  • Boolean arrays used for filtering must be the same shape as the array being filtered.
  • Use parentheses when combining conditions to avoid operator precedence issues.
  • Boolean indexing returns a copy, not a view of the original array.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review