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
scores = np.array([55, 82, 47, 91, 68])scores > 60 # [False True False True True] — a boolean maskscores[scores > 60] # [82 91 68] — only the passing scores
Combining conditions
scores[(scores > 50) & (scores < 90)] # [55 82 68]scores[~(scores > 60)] # values NOT over 60
Assigning through a mask
scores[scores < 60] = 0 # fail → 0np.where(scores >= 60, "pass", "fail") # vectorised if/else
Key takeaways
- 01A comparison yields a boolean mask; arr[mask] keeps the elements that pass.
- 02Combine conditions with & | ~ (not and/or), and parenthesise each one.
- 03Assign through a mask (arr[arr < x] = 0) for conditional updates.
- 04np.where(cond, a, b) is a vectorised if/else across the array.
