Module 2 · Lesson 2
Boolean Indexing
Comparing an array to a value produces a boolean mask — an array of
True/False the same shape as the original. Indexing with that mask
returns only the elements where it’s True. To combine conditions, you
must use the bitwise operators &, |, ~ (NOT Python’s and/or/not
— those don’t work elementwise and will raise an error on arrays with more
than one element). np.where(condition, a, b) is the vectorized
if/else: pick from a where condition is True, else from b.
Two more things come up constantly once you’re working with masks. First,
True/False behave as 1/0 in arithmetic, so mask.sum() counts how
many elements are True — a quick way to count matches without reaching
for the full aggregation toolkit (Module 4 covers .sum(), .mean(), and
friends in depth). Second, indexing itself never mutates anything, but if
you’re about to change values and want to leave the original untouched,
call .copy() first to get an independent array — Lesson 4 covers views
vs. copies in full.
arr = np.array([3, -1, 7, -5, 2, 0, 9])
mask = arr > 0
print(mask)
print(arr[mask]) # positive values only
print(arr[(arr > 0) & (arr < 8)]) # combine with & , not "and"
clipped = np.where(arr < 0, 0, arr) # replace negatives with 0
print(clipped)
arr[arr < 0] = 0 # assign through a mask, in place
print(arr)
Output:
[ True False True False True False True]
[3 7 2 9]
[3 7 2]
[3 0 7 0 2 0 9]
[3 0 7 0 2 0 9]
Clip to a range
Write clip_range(arr, low, high) that returns a new array where every
value below low is replaced by low, and every value above high is
replaced by high (values already in range are unchanged). Do not use
np.clip — build it from boolean masks and np.where (or boolean
assignment on a copy) to practice the mechanics.
💡 Hint
Make a copy first (out = arr.copy()), then assign through two masks: out[out < low] = low and out[out > high] = high.
✅ Solution
def clip_range(arr, low, high):
out = arr.copy()
out[out < low] = low
out[out > high] = high
return out
Count values in a band
Write count_in_band(arr, low, high) that returns how many elements of
arr satisfy low <= x <= high, as a plain Python int.
💡 Hint
Combine two comparisons with &, then .sum() the boolean mask — True counts as 1. Wrap the result in int(...).
✅ Solution
def count_in_band(arr, low, high):
mask = (arr >= low) & (arr <= high)
return int(mask.sum())