Sub topic 6
Boolean masks: filtering with conditions
This chapter assumes you can create arrays with np.array, np.arange, and reshape. It also assumes you know integer indexing and slicing, and what an array's shape and dtype are. Here you will build a boolean mask from a comparison and use it to pick out elements.
What a mask is
A comparison such as data > 0 is applied to every element at once. The result is a new array of the same shape whose dtype is bool. This array is called a boolean mask. Each True marks an element to keep, and each False marks an element to drop.
If you put the mask inside square brackets, NumPy returns only the elements where the mask is True.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(mask) # [ True False True False False True]
print(mask.dtype) # bool
print(data[mask]) # [4 7 2]
print(data[data > 0]) # [4 7 2], the same thing without a named maskThe diagram shows the two steps.
Any comparison works
All of the usual operators produce masks: <, <=, >, >=, ==, and !=. You can also compare against another array of the same shape, or build a mask from an expression.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(data[data % 2 == 0]) # [4 0 2], even values
print(data[data != 0]) # [ 4 -1 7 -5 2]
print(data[np.abs(data) > 3]) # [ 4 7 -5]Functions that return boolean arrays also work as masks. np.isnan(x) is a common one, because x == np.nan is always False and cannot find missing values.
Masks on two-dimensional arrays
When the mask has the same shape as the array, NumPy picks the matching elements and returns them as a flattened 1-D array. The result cannot keep a 2-D shape, because each row may keep a different number of elements.
A mask can also be one-dimensional and select whole rows or columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a % 2 == 0)
# [[ True False True False]
# [ True False True False]
# [ True False True False]]
print(a[a % 2 == 0]) # [ 0 2 4 6 8 10]
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]]The length of a 1-D mask must match the axis it indexes. A mask of length 3 works on the rows of a, which has 3 rows. It raises an IndexError if you try it on the 4 columns.
Counting and testing with masks
True counts as 1 and False counts as 0 in arithmetic. This lets you summarize a mask without filtering anything.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(mask.sum()) # 3, how many elements match
print(mask.mean()) # 0.5, the fraction that match
print(mask.any()) # True, at least one matches
print(mask.all()) # False, not every element matchesUse np.count_nonzero(mask) if you only want the count. To get the positions of the matches instead of the values, use np.nonzero(mask) or np.flatnonzero(mask).
The result is a copy
Indexing with a boolean mask always returns a new array. Changing the result does not change the original.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
picked = data[data > 0]
picked[0] = 100
print(picked) # [100 7 2]
print(data) # [ 4 -1 7 0 -5 2], unchangedThis is the opposite of a basic slice, which shares memory with the original. Writing through a mask on the left side of = is a different operation and does change the original. That is covered in a later chapter.
Common errors
- Wrong mask length. A 1-D mask must have the same length as the axis it indexes.
- Using
andoror. Python'sandandorraise aValueErroron arrays with more than one element. Use&and|instead, as the next chapter explains. - Expecting the original shape back. A full-shape mask always gives a 1-D result.
Exercise
Given a = np.array([[3, 8], [5, 1], [9, 6]]), write one expression that returns the rows whose second column is greater than 5. What does it return, and what is the shape of the result?
Show answer
a[a[:, 1] > 5]. The 1-D mask is [True False True], so it returns [[3 8] [9 6]], an array of shape (2, 2).
Exercise
Why does data[mask] leave data unchanged when you modify the result?
Show answer
Boolean-mask indexing returns a copy, not a view, so the result does not share memory with data.