Boolean Masking and Filtering
NumPy lets you filter arrays using boolean conditions — also called masking.
You can compare values in an array, and NumPy will return a new array with only the values that match the condition.
Boolean Arrays
A comparison like arr > 10
returns a new array of True
or False
values.
arr = np.array([5, 12, 18, 7])
mask = arr > 10
print(mask) # [False True True False]
Filtering Values
You can use the boolean array as a mask to filter the original array.
print(arr[mask]) # [12 18]
Or write it in one line:
print(arr[arr > 10]) # [12 18]
This is very useful for filtering rows, selecting values in a range, or finding outliers.
Summary
- Use comparisons (
>
,<
,==
, etc.) to create boolean masks - Apply the mask to select only the values you want
- Works on both 1D and 2D arrays
What’s Next
You’ll now practice filtering arrays using conditions in a Jupyter Notebook.