Skip to main content
Albero Academy

Boolean Masking

Filter arrays by condition — the single most useful NumPy technique.

Indexing & Slicing10 min

Comparing an array to a value produces a boolean array; indexing with it keeps only the elements that pass. This replaces filtering loops entirely and is, in practice, the most useful thing you'll do in NumPy.

Filtering with a mask

the core trick
scores = np.array([55, 82, 47, 91, 68])
scores > 60 # [False True False True True] — a boolean mask
scores[scores > 60] # [82 91 68] — only the passing scores

Combining conditions

multiple conditions
scores[(scores > 50) & (scores < 90)] # [55 82 68]
scores[~(scores > 60)] # values NOT over 60

Assigning through a mask

conditional update
scores[scores < 60] = 0 # fail → 0
np.where(scores >= 60, "pass", "fail") # vectorised if/else

Key takeaways

  1. 01A comparison yields a boolean mask; arr[mask] keeps the elements that pass.
  2. 02Combine conditions with & | ~ (not and/or), and parenthesise each one.
  3. 03Assign through a mask (arr[arr < x] = 0) for conditional updates.
  4. 04np.where(cond, a, b) is a vectorised if/else across the array.

Finished this chapter?

Mark it complete to track your progress through NumPy.