Sub topic 7
Boolean Masks and Fancy Indexing
This chapter assumes you can create arrays, read shape and dtype, use basic slicing, and tell a view from a copy. Basic slicing selects regular patterns such as a[1:4]. Two other kinds of indexing select arbitrary elements: boolean masks and integer arrays, also called fancy indexing.
Boolean masks
A comparison on an array returns a boolean array of the same shape, called a mask. Indexing with the mask keeps the elements where it is True. Assigning through a mask changes the original array.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
print(a[a > 0]) # [3 4 9]
a[a < 0] = 0
print(a) # [3 0 4 0 9]To combine conditions, use &, |, and ~, and wrap each comparison in parentheses. The Python keywords and and or don't work on arrays.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
mask = (a > 0) & (a < 9)
print(mask) # [ True False True False False]
print(a[mask]) # [3 4]On a 2-D array, a mask of the same shape returns a flat 1-D result, because the selected elements no longer form a rectangle.
Fancy indexing
Indexing with a list or array of integers picks those positions, in the order given. Positions can repeat.
import numpy as np
a = np.array([3, 0, 4, 0, 9])
print(a[[0, 2]]) # [3 4]
print(a[[4, 0, 0]]) # [9 3 3]
m = np.arange(12).reshape(3, 4)
print(m[[2, 0]]) # rows 2 and 0
print(m[[0, 1, 2], [1, 2, 3]]) # [ 1 6 11]
print(m[m % 2 == 0]) # [ 0 2 4 6 8 10]With two index arrays, NumPy pairs them element by element. The call m[[0, 1, 2], [1, 2, 3]] reads positions (0,1), (1,2), and (2,3). It doesn't select a 3×3 block.
Copies, not views
Reading with a mask or an integer array returns a copy. Changing the result leaves the source alone. This is the opposite of basic slicing.
import numpy as np
a = np.array([3, 0, 4, 0, 9])
b = a[a > 0]
b[0] = 100
print(a) # [3 0 4 0 9], unchanged| Indexing style | Example | Result on read | Shape of result |
|---|---|---|---|
| Basic slice | `a[1:4]` | View | Rectangular |
| Boolean mask | `a[a > 0]` | Copy | 1-D |
| Integer array | `a[[0, 2]]` | Copy | Follows the index array |
Common errors
- Using
andoror.a[(a > 0) and (a < 9)]raisesValueError: The truth value of an array ... is ambiguous. Use&and|. - Missing parentheses. In
a > 0 & a < 9, the&binds first and the expression fails or gives wrong results. - Repeated indices in an update. Each position is updated once, so repeats are not accumulated.
import numpy as np
x = np.zeros(3, dtype=int)
x[[0, 0, 1]] += 1
print(x) # [1 1 0], not [2 1 0]
y = np.zeros(3, dtype=int)
np.add.at(y, [0, 0, 1], 1)
print(y) # [2 1 0]Exercise
Given a = np.array([5, 12, -3, 8, 20]), write one statement that caps every value above 10 at 10 and changes the original array. What does a hold afterwards?
Show answer
a[a > 10] = 10. Assigning through a mask writes into a itself, so a becomes [ 5 10 -3 8 10].