Boolean Masking
Filter array elements using conditions — the NumPy way to query data
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Boolean masking lets you filter array elements using a condition. The condition creates a boolean array (mask), which is used to select elements.
a = np.array([3, 7, 1, 9, 2, 8, 4])
mask = a > 5 # [False, True, False, True, False, True, False]
a[mask] # [7, 9, 8] — only values where True
# Shorthand (most common usage):
a[a > 5] # [7, 9, 8]
a[a % 2 == 0] # [2, 8, 4] — even numbers onlyCombined conditions:
python a[(a > 3) & (a < 8)] # [7, 4] — use & not 'and' a[(a < 2) | (a > 7)] # [1, 9, 8] — use | not 'or'
Modifying with a mask:
python a[a < 0] = 0 # set all negatives to zero (common data cleaning)
np.where() — conditional replacement:
python np.where(a > 5, 1, 0) # 1 where condition is True, 0 elsewhere
Examples
Data cleaning with boolean masking
Boolean masking is the standard way to filter bad data
import numpy as np
temps = np.array([22, -999, 25, 18, -999, 30, 21])
# -999 is a missing value sentinel
valid = temps[temps != -999]
print(valid) # [22, 25, 18, 30, 21]
print(valid.mean()) # 23.2
# Or replace in-place:
temps[temps == -999] = np.nanHow well did you understand this?