Boolean Masking and Filtering
NumPy allows you to filter arrays using boolean conditions, a technique called masking.
You compare values in an array, and NumPy returns a new array with only the values that meet the condition.
Boolean Arrays
A comparison like arr > 10
produces a new array of True
or False
values.
Boolean Arrays
arr = np.array([5, 12, 18, 7])
mask = arr > 10
print(mask) # [False True True False]
Filtering Values
You can use this boolean array as a mask to filter the original array.
Filtering Values
print(arr[mask]) # [12 18]
Or write it more directly:
Filtering Values another way
print(arr[arr > 10]) # [12 18]
Masking is especially useful for filtering rows, selecting ranges, or identifying outliers.
Summary
- Use comparisons (
>
,<
,==
, etc.) to create boolean masks - Apply the mask to select only the values you want
- Works with both 1D and 2D arrays
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.