NumPy · Lesson 1.3
Boolean masks
Use True/False arrays to filter values, count them, and replace values that match a rule.
1A comparison gives a mask
Comparing an array with a value gives an array of True and False, one per value. This is called a mask.
import numpy as np scores = np.array([72, 45, 88, 60, 91, 39]) scores >= 60
Practice
Store a mask that is True for every response time over 2.0 seconds.
import numpy as np response = np.array([1.2, 2.8, 0.9, 3.4, 2.0, 2.1]) result = ...
2Filter with a mask
Put a mask inside the brackets and you get only the values where it's True. arr[arr > 50] reads as "the values of arr that are over 50".
import numpy as np scores = np.array([72, 45, 88, 60, 91, 39]) scores[scores >= 60]
Practice
Store the order amounts that are under 20.
import numpy as np amounts = np.array([35.5, 12.0, 18.75, 50.0, 7.25, 22.0]) result = ...
3Combine rules, count matches
Join masks with & (and), | (or) and ~ (not), with brackets round each part. True counts as 1, so .sum() counts matches and .mean() gives the share.
import numpy as np ages = np.array([17, 25, 34, 41, 19, 66, 52]) working_age = (ages >= 18) & (ages < 65) print(working_age.sum(), "people,", working_age.mean().round(2), "of everyone")
Practice
Store how many sessions lasted between 20 and 50 minutes, including both ends.
import numpy as np minutes = np.array([15, 20, 33, 51, 50, 8, 47, 62, 29]) result = ...
4Replace values with np.where
np.where(mask, a, b) takes a where the mask is True and b where it's False. It's the array version of an if/else.
import numpy as np scores = np.array([72, 45, 88, 60, 91, 39]) np.where(scores >= 60, "pass", "fail")
Practice
Some stock counts went below zero because of a data error. Store stock with every negative value replaced by 0, using np.where.
import numpy as np stock = np.array([5, -2, 14, 0, -7, 3]) result = ...
Quick check
You want ages from 18 to 64. Which line works?