NumPy Array Filter
Filtering a NumPy array means extracting only the elements that satisfy a condition, using a boolean index array to pick them out.
What Is a Boolean Index Array?
A boolean index array is an array of True and False values, the same length as the array you want to filter. When you index an array with a boolean array, NumPy keeps only the elements where the corresponding position is True and discards the rest. This is the foundation of filtering in NumPy — everything else builds on this idea.
Example
import numpy as np
arr = np.array([41, 55, 62, 78, 83, 90])
# A hand-written boolean index array
mask = np.array([True, False, True, False, True, False])
print(arr[mask])
# [41 62 83]Filtering with Conditions Directly
Writing out a boolean array by hand doesn't scale, so in practice you generate it directly from a condition applied to the array itself. Any comparison — greater than, less than, equal to, not equal to — produces a boolean array automatically, which you can then use immediately as an index.
Example
import numpy as np
arr = np.array([41, 55, 62, 78, 83, 90])
# The comparison itself produces the boolean array
condition = arr > 60
print(condition)
# [False False True True True True]
# Use it immediately to filter
print(arr[arr > 60])
# [62 78 83 90]
# Filtering for even numbers
print(arr[arr % 2 == 0])
# [62 78 90]Combining Multiple Conditions
To filter on more than one condition at once, combine boolean arrays with the bitwise operators & (and), | (or), and ~ (not) — not Python's regular 'and'/'or' keywords, which don't work element-wise on arrays. Each individual condition must be wrapped in parentheses because of operator precedence.
Example
import numpy as np
arr = np.array([41, 55, 62, 78, 83, 90])
# Values between 50 and 85 (inclusive)
result = arr[(arr >= 50) & (arr <= 85)]
print(result)
# [55 62 78 83]
# Values less than 50 OR greater than 85
result2 = arr[(arr < 50) | (arr > 85)]
print(result2)
# [41 90]
# Everything that is NOT even
result3 = arr[~(arr % 2 == 0)]
print(result3)
# [41 55 83]- Always use & , | , and ~ for combining conditions on arrays — Python's and/or/not only work on single boolean values, not element-wise on arrays.
- Wrap each condition in parentheses, e.g. (arr > 50) & (arr < 90); without them, operator precedence rules can throw an error or give the wrong result.
- np.logical_and(), np.logical_or(), and np.logical_not() are readable alternatives to &, |, and ~ when a condition gets complex.
- Filtering with a boolean array always returns a new array (a copy), so changing the filtered result never affects the original array.
Exercise: NumPy Array Filter
How do you filter a NumPy array using a boolean condition?