Creating Boolean Masks with Comparisons
Introduction
Welcome to Boolean Arrays and Masks. This is your first lesson in the course, and we’ll begin by learning how to ask questions about many array values at once. As you may recall from earlier courses, NumPy lets us perform operations across arrays without writing a Python loop for each element. Here, we’ll use comparisons to produce arrays of True and False answers, then learn to recognize those results as boolean masks. These masks will be useful throughout the course.
Comparing an Array to a Number
Suppose we have phone battery levels and want to find which phones are below 20%. A loop could check each level one by one, but NumPy lets us ask the question across the whole array with one comparison. The expression battery < 20 compares every value to 20 and stores the answers in low. We can print the answers to inspect the result. As always, we import NumPy as np first; the later snippets in this lesson use the same import.
The printed line contains one answer for each battery level. True marks a value below 20, while False marks one that is not. In the next step, we’ll also check the data type of this result.
The Result Is a Boolean Mask
The comparison’s result is not a single answer for the whole array. It is a new array with the same length as battery, containing one answer for each element. Its data type is bool, which means its values are True or False. We call this pattern a boolean mask: it records which positions meet a condition. NumPy prints array elements without commas, so the displayed values are still separate answers, not one combined result. Printing low.dtype confirms the mask’s data type.
Comparing Two Same-Length Arrays
We can also compare two arrays element by element. Here, actual == planned checks whether each delivery arrived at its planned time. The arrays have the same length, so NumPy compares values at matching positions: the first actual time with the first planned time, the second with the second, and so on. Each position produces True when the times match and False when they differ.
The printed mask shows which deliveries were exactly on schedule. Notice that the comparison returns an array of answers, not one answer for the two arrays as a whole.
