Boolean Masks
Filter with Mask
Keep only the values where a boolean mask is True. A zip loop pairs each value
with its mask entry; an if-check inside the loop decides whether to append. The
replay shows filtered growing only when m is True, making the selection
criterion explicit.
By hand
With NumPy
a[m] selects every element of a where the corresponding element of the
boolean array m is True. NumPy calls this boolean indexing. The snapshot
shows the input, the mask, and the filtered result with its smaller shape.
naive.py
values = [3, 7, 2, 9, 1, 5]
mask = [False, True, False, True, False, True]
filtered = []
for v, m in zip(values, mask):
if m:
filtered.append(v)
print('RESULT:', filtered)
library.py
import numpy as np
values = [3, 7, 2, 9, 1, 5]
mask = [False, True, False, True, False, True]
a = np.array(values)
m = np.array(mask)
filtered = a[m]
print('a: shape:', a.shape, 'dtype:', a.dtype, 'values:', a.tolist())
print('mask: shape:', m.shape, 'dtype:', m.dtype, 'values:', m.tolist())
print('filtered: shape:', filtered.shape, 'dtype:', filtered.dtype, 'values:', filtered.tolist())
print('RESULT:', filtered.tolist())
a: shape: (6,) dtype: int64 values: [3, 7, 2, 9, 1, 5]
mask: shape: (6,) dtype: bool values: [False, True, False, True, False, True]
filtered: shape: (3,) dtype: int64 values: [7, 9, 5]
RESULT: [7, 9, 5]
Implementation notes
- Boolean indexing (
a[mask]) returns a copy, not a view. Modifying the result does not affecta. - The output shape is
(count_of_True,)— determined at runtime, not known from the input shape alone. - The mask is typically built by a comparison (
a > k) rather than written by hand — seemask-from-thresholdfor that pattern. Chaining both steps:a[a > k]selects in one expression. - For the equivalent pure-Python pattern see
filter-by-thresholdin the python-data-basics book. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.