Summarizing Masked Data
Introduction
Welcome back to Summarizing Data. We’re now in lesson four, and we’re ready to combine two tools from earlier lessons: masks select matching values, and aggregates summarize values. Together, they let us answer focused questions, such as finding the average of passing scores, without writing a loop. We’ll practice selecting and summarizing in one line or in separate steps, building a mask from an aggregate, using a mask from one array to summarize another, and handling the case where nothing matches.
Summarize a Masked Subset
A mask can narrow an array to just the values we care about. As you may recall from previous units, comparing an array with a condition creates a Boolean mask, and using that mask in square brackets selects matching values. We can pass that selection directly to an aggregate. Here, the condition keeps scores of 70 or higher, and np.mean averages only those scores. As always, we import NumPy as np first; the later snippets in this lesson use the same import.
The expression inside np.mean evaluates to an array containing the passing scores. The result is their average, 83.5:
The selection is an array, so we can use other aggregates on it, too, such as np.sum, np.min, or np.max.
Selecting and Summarizing in One Line vs. Two Steps
We can select values and summarize them in one expression, as in the previous example. Alternatively, we can first save the mask in a variable. Separating the steps is useful when we want to inspect the selected values or reuse the mask. In this example, the mask marks the passing scores, and the print statements show which values it selects and their average.
The selected values are 72, 85, 90, 88, 71, and 95, and their average is the same 83.5 as in the one-line form:
In the one-line form, the condition appears inside the selection. In the two-step form, we keep the condition’s result in passed so we can use it by name.

