Sub topic 6
Boolean Masks: Filtering with Conditions
This chapter assumes you can create arrays with np.array, np.arange, and reshape, and that you know what shape and dtype mean. It also assumes you have seen integer indexing and slicing from earlier chapters. Here you will learn how a comparison turns an array into a boolean array, and how that boolean array selects elements. The next chapter covers combining several conditions and assigning through masks.
What a boolean mask is
A boolean mask is an array of True and False values. NumPy comparison operators (>, <, >=, <=, ==, !=) work element by element and return a mask with the same shape as the input.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(mask.dtype) # bool
print(mask) # [ True False True False False True]
print(mask.shape) # (6,)The mask is an ordinary array with dtype bool. You can store it in a variable, pass it to functions, and reuse it on other arrays of a matching shape.
Selecting with a mask
Put the mask inside square brackets. NumPy keeps the elements at positions where the mask is True and drops the rest.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(data[mask]) # [4 7 2]
print(data[data > 0]) # [4 7 2], same thing in one stepThe one-step form data[data > 0] is the idiom you will see most often. Read it as "the elements of data where data is greater than zero."
The result is a copy
Boolean indexing always returns a new array that does not share memory with the original. This differs from basic slicing, which returns a view. The reason is that the selected elements are scattered through memory with no regular stride, so NumPy cannot describe them as a view.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
picked = data[data > 0]
picked[0] = 100
print(data) # [ 4 -1 7 0 -5 2], unchanged
print(np.shares_memory(data, picked)) # FalseWriting to the result of a mask selection does not change the original. To change the original, put the mask on the left side of an assignment, as in data[mask] = 0. That form is covered in the chapter on assignment through masks.
Counting and testing with masks
Because True counts as 1 and False counts as 0, you can do arithmetic on a mask. These calls are common ways to ask questions about your data without selecting anything.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(mask.sum()) # 3, how many elements satisfy the condition
print(np.count_nonzero(mask)) # 3, same count
print(mask.mean()) # 0.5, the fraction that satisfy it
print(mask.any()) # True, at least one is positive
print(mask.all()) # False, not all are positive
print(np.flatnonzero(mask)) # [0 2 5], positions of the True valuesnp.flatnonzero converts a mask to integer positions. Indexing with those positions, data[np.flatnonzero(mask)], gives the same values as data[mask]. This connection matters later, when you meet fancy indexing with integer arrays.
Masks on two-dimensional arrays
A comparison on a 2-D array produces a 2-D mask. Indexing with a mask of the full shape returns a flattened 1-D array of the matching values, taken in row-major order (row by row, left to right).
import numpy as np
a = np.arange(12).reshape(3, 4)
m = a > 5
print(m)
# [[False False False False]
# [False False True True]
# [ True True True True]]
print(a[m]) # [ 6 7 8 9 10 11]
print(a[a % 2 == 0]) # [ 0 2 4 6 8 10]The result is 1-D because the selected elements no longer form a rectangle in general. NumPy has no way to keep the 2-D layout when some rows lose more elements than others.
Masks along one axis
A mask does not have to match the whole shape. A 1-D mask can select whole rows or whole columns if its length matches that axis.
import numpy as np
a = np.arange(12).reshape(3, 4)
row_mask = a[:, 0] > 0 # [False True True]
print(a[row_mask])
# [[ 4 5 6 7]
# [ 8 9 10 11]]
col_mask = a[0] > 1 # [False False True True]
print(a[:, col_mask])
# [[ 2 3]
# [ 6 7]
# [10 11]]In the first case the mask indexes axis 0, so it picks rows. In the second case the slice : leaves axis 0 alone and the mask indexes axis 1, so it picks columns. These results keep their 2-D shape because whole rows or columns are kept.
You can also reduce a full-shape mask along an axis to get a 1-D mask. m.any(axis=1) asks "does this row contain at least one match?" and m.all(axis=0) asks "does this column match everywhere?"
import numpy as np
a = np.arange(12).reshape(3, 4)
m = a > 5
print(m.any(axis=1)) # [False True True]
print(m.all(axis=0)) # [False False False False]
print(a[m.any(axis=1)])
# [[ 4 5 6 7]
# [ 8 9 10 11]]Using one array to filter another
The mask only needs to have the right shape. It can come from a different array. This is how you filter one column of data by the values in another, which is common when you hold related values in parallel arrays.
import numpy as np
names = np.array(["ann", "bob", "cy"])
scores = np.array([88, 92, 75])
high = scores >= 80
print(names[high]) # ['ann' 'bob']
print(scores[names != "bob"]) # [88 75]Comparisons also work on string arrays, as the names != "bob" line shows.
Shape rules and the length error
For a 1-D array, the mask must have exactly the same length. If the lengths differ, NumPy raises an IndexError.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
short_mask = np.array([True, False])
try:
data[short_mask]
except IndexError as err:
print(err)
# boolean index did not match indexed array along axis 0;
# size of axis 0 is 6 but size of corresponding boolean axis is 2The message tells you which axis failed and both sizes. This error usually means the mask was built from a different array than the one you are indexing. Check mask.shape against the axis you meant to filter.
Edge cases
Nothing matches
If no element satisfies the condition, you get an empty array, not an error. Its dtype is preserved.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
empty = data[data > 100]
print(empty) # []
print(empty.shape) # (0,)
print(empty.dtype) # int64 on most platformsCode downstream must handle size zero. For example, empty.max() raises a ValueError, so check empty.size first if the case can occur.
Floating-point equality
== on floats compares exact bit patterns, so tiny rounding differences make a mask miss values you expected. Use np.isclose to compare with a tolerance.
import numpy as np
x = np.array([0.1 + 0.2, 0.3])
print(x == 0.3) # [False True]
print(np.isclose(x, 0.3)) # [ True True]The value 0.1 + 0.2 is stored as 0.30000000000000004, which is not equal to 0.3. Prefer np.isclose whenever floats come from arithmetic.
NaN values
NaN (not a number) is never equal to anything, including itself. A comparison such as v == np.nan is False everywhere, so it cannot find missing values. Use np.isnan to build the mask.
import numpy as np
v = np.array([1.0, np.nan, 3.0])
print(v == np.nan) # [False False False]
print(np.isnan(v)) # [False True False]
print(v[~np.isnan(v)]) # [1. 3.]
print(v[v > 1]) # [3.], NaN compares as FalseThe ~ operator inverts a mask, turning True into False and the reverse. The next chapter covers it along with & and |.
Python's `and` does not work on masks
Chaining conditions with and, or, or not raises ValueError: The truth value of an array with more than one element is ambiguous. Python asks for a single True or False, and an array of many values cannot supply one. The next chapter shows the element-wise operators that replace these keywords.
A short worked example
This example puts several ideas together. You have hourly temperature readings and want to know how many hours were above freezing, the average of those readings, and which hours they were.
import numpy as np
temps = np.array([-3.5, -1.0, 0.5, 2.0, 4.5, 1.0, -0.5, -2.0])
hours = np.arange(8)
above = temps > 0
print(above.sum()) # 4 readings are above freezing
print(temps[above].mean()) # 2.0, the average of 0.5, 2.0, 4.5, 1.0
print(hours[above]) # [2 3 4 5], the hours when it was above freezingOne mask drives three questions. The mask is computed once from temps and reused on hours, which has the same shape.
Summary of behavior
| Operation | Result |
|---|---|
| `a > 0` | Boolean array, same shape as `a` |
| `a[mask]` with a full-shape mask | 1-D copy of the matching elements, in row-major order |
| `a[row_mask]` with a 1-D mask | Selected rows, 2-D, a copy |
| `a[:, col_mask]` | Selected columns, 2-D, a copy |
| `mask.sum()` or `np.count_nonzero(mask)` | Number of `True` values |
| `np.flatnonzero(mask)` | Integer positions of the `True` values |
| Mask of wrong length | `IndexError` |
| No matches | Empty array, not an error |
Exercise
Given a = np.arange(12).reshape(3, 4), what does a[a % 3 == 0] return, and what is the shape of the result? Why is it not 2-D?
Show answer
It returns [0 3 6 9] with shape (4,). The mask has the full shape of a, and the matching elements are scattered across rows with different counts per row, so NumPy cannot keep a rectangular layout. A full-shape boolean index always returns a 1-D copy in row-major order.
Exercise
You have temps = np.array([12.5, 18.0, 25.3, 30.1]) and days = np.array(["Mon", "Tue", "Wed", "Thu"]). Write one expression that returns the days where the temperature was above 20, and one that counts how many such days there are.
Show answer
days[temps > 20] returns ['Wed' 'Thu'], and (temps > 20).sum() (or np.count_nonzero(temps > 20)) returns 2. The mask comes from temps and is reused on days because both arrays have the same length.
Exercise
A learner writes v[v == np.nan] to select the missing values in a float array v and gets an empty array even though v contains NaN. What is the cause, and what is the fix?
Show answer
NaN is never equal to anything, including itself, so v == np.nan is False for every element and the mask selects nothing. Use v[np.isnan(v)] to select the NaN values, or v[~np.isnan(v)] to drop them.