Counting with Boolean Masks
Introduction
Welcome back to Summarizing Data. We’re now in the second lesson of the course, building on the aggregate functions we explored last time. Today, we’ll use np.sum and np.mean with a boolean mask to answer questions such as “How many students passed?” and “What fraction of the scores reached the passing mark?” By the end, we’ll be able to count matching values and measure their share without writing a loop.
True Counts as 1: Revealing the Numbers Behind a Mask
As you may recall from earlier courses, a comparison creates a boolean mask: an array of True and False values. NumPy can convert those values to integers with astype(int). Each True becomes 1, and each False becomes 0. Seeing those numbers makes it easier to understand how an aggregate can count matches. As always, we import NumPy as np first; the later snippets in this lesson use the same import.
The comparison marks each score of at least 70 as True. Converting the mask to integers reveals a 1 for each passing score and a 0 for the one that did not pass:
Counting Matches with np.sum on a Mask
Now that the mask’s values are visible as zeros and ones, we can use np.sum to count the matches. Adding the mask is equivalent to adding one for every True and zero for every False. We can store that count in a variable or print it directly.
np.sum(passed) adds the mask values without changing the original mask. Since six scores meet the condition, the count is:
Writing Masks Inline: Counting Without a Variable
A named mask is useful when we want to inspect or reuse it. If we only need the count once, we can put the comparison directly inside np.sum. This is the same approach as before, just with one fewer variable.
The comparison creates a temporary mask, and np.sum counts its True values. Only 27, 29, and 26 are above 25, so the printed count is:
