Sub topic 5
Boolean masks and integer-array indexing
This chapter assumes you know basic slicing (a[1:3, :2]), the difference between a view and a copy, and how comparison operators work elementwise on arrays. It covers the two ways to select data that basic slicing cannot express: selecting by a condition, and selecting by a list of positions. Both are called advanced indexing, and both return copies.
Boolean masks
A comparison on an array returns a new array of the same shape with dtype bool. This array is called a mask. Indexing with a mask keeps the elements where the mask is True.
import numpy as np
a = np.array([4, -1, 7, 0, -5, 9])
mask = a > 0
print(mask) # [ True False True False False True]
print(a[mask]) # [4 7 9]
print(a[~mask]) # [-1 0 -5]The result of a[mask] is always one-dimensional when the mask has the same shape as the array. NumPy cannot keep a rectangular layout when each row may lose a different number of elements, so it flattens the survivors in row-major order.
Combining conditions
Python's and, or and not ask for a single truth value from the whole array, which raises a ValueError. Use the elementwise operators &, | and ~ instead. These operators bind more tightly than comparisons, so each comparison needs its own parentheses.
import numpy as np
a = np.array([4, -1, 7, 0, -5, 9])
print(a[(a > 0) & (a < 8)]) # [4 7]
print(a[(a < 0) | (a > 8)]) # [-1 -5 9]Without the parentheses, a > 0 & a < 8 is parsed as a > (0 & a) < 8, which fails or gives the wrong answer.
Counting and locating
A mask is also a useful value in its own right. True counts as 1 and False as 0, so reductions work directly on it.
import numpy as np
a = np.array([4, -1, 7, 0, -5, 9])
mask = a > 0
print(mask.sum()) # 3, how many elements pass
print(mask.mean()) # 0.5, the fraction that pass
print(mask.any(), mask.all()) # True False
print(np.flatnonzero(mask)) # [0 2 5], positions of the True valuesnp.flatnonzero converts a mask into integer positions, which connects this section to the next one.
Assigning through a mask
A mask on the left side of an assignment writes into the original array. This is the usual way to clip, replace or zero out values in place.
import numpy as np
b = np.array([4, -1, 7, 0, -5, 9])
b[b < 0] = 0
print(b) # [4 0 7 0 0 9]
b[b > 5] *= 2
print(b) # [ 4 0 14 0 0 18]Reading with a mask returns a copy, but assigning with a mask modifies the array. Python translates b[mask] = value into a call to __setitem__, which writes into b. A read such as y = b[mask] calls __getitem__, which builds a new array.
Masks on one axis
A mask does not have to match the full shape of the array. A one-dimensional mask can select whole rows or whole columns.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[m % 2 == 0]) # [ 0 2 4 6 8 10]
print(m[np.array([True, False, True])])
# [[ 0 1 2 3]
# [ 8 9 10 11]]
print(m[m[:, 0] > 0]) # rows whose first element is positive
# [[ 4 5 6 7]
# [ 8 9 10 11]]
print(m[:, m[0] > 1]) # columns where the first row exceeds 1
# [[ 2 3]
# [ 6 7]
# [10 11]]The mask's length must equal the length of the axis it indexes. A length mismatch raises an IndexError.
Integer-array indexing
Instead of a condition, you can pass the positions you want. The index can be a list or an integer array. The result contains the elements at those positions, in the order you gave them.
import numpy as np
v = np.array([10, 20, 30, 40, 50])
print(v[[0, 2, 2, -1]]) # [10 30 30 50]
idx = np.array([[0, 1],
[3, 4]])
print(v[idx])
# [[10 20]
# [40 50]]Three properties follow from this example:
- The order of the result follows the order of the index, not the order of the data.
- Positions can repeat, and negative positions count from the end as in ordinary indexing.
- The result has the shape of the index array, not the shape of
v.
An index that is out of range raises an IndexError. For example, v[[0, 7]] fails because v has only five elements.
Sorting and ranking with index arrays
Functions such as np.argsort and np.argmax return positions, so their results are meant to be used as integer indexes. Reuse the same order to rearrange several parallel arrays.
import numpy as np
scores = np.array([72, 95, 88, 61])
names = np.array(["Ana", "Ben", "Caro", "Dev"])
order = np.argsort(scores)[::-1] # positions from highest score to lowest
print(order) # [1 2 0 3]
print(scores[order]) # [95 88 72 61]
print(names[order]) # ['Ben' 'Caro' 'Ana' 'Dev']Indexing a 2D array
With one index array, you select whole rows.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[[2, 0]])
# [[ 8 9 10 11]
# [ 0 1 2 3]]With two index arrays, NumPy pairs them element by element. The first array supplies row numbers, the second supplies column numbers, and the result has one element per pair.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[[0, 1, 2], [1, 2, 3]]) # [ 1 6 11], elements (0,1), (1,2), (2,3)
print(m[[0, 2], [1, 3]]) # [ 1 11], elements (0,1) and (2,3), not a 2x2 blockThis pairing surprises many learners, who expect the second call to return a 2x2 block. The two index arrays are broadcast against each other, which is the same mechanism that later chapters cover for arithmetic. To select the block formed by rows 0 and 2 and columns 1 and 3, give the row index a column shape, or use np.ix_, which does this for you.
import numpy as np
m = np.arange(12).reshape(3, 4)
rows = [0, 2]
cols = [1, 3]
print(m[np.ix_(rows, cols)])
# [[ 1 3]
# [ 9 11]]
print(m[np.array(rows)[:, np.newaxis], cols]) # same resultMixing slices with index arrays
A slice and an index array can appear together. The slice keeps its axis as a range, and the index array selects positions along its own axis.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[1:, [0, 3]])
# [[ 4 7]
# [ 8 11]]Assignment with repeated positions
Assigning through an integer array works like assigning through a mask, but repeated positions need care. When a position appears twice, the last value written wins. Augmented assignment does not accumulate over repeats either, because z[idx] += 1 reads all the values first and then writes them back.
import numpy as np
z = np.zeros(3, dtype=int)
z[[0, 0, 1]] = [1, 2, 3]
print(z) # [2 3 0], the last write to position 0 wins
z = np.zeros(3, dtype=int)
z[[0, 0, 1]] += 1
print(z) # [1 1 0], position 0 is incremented once, not twice
z = np.zeros(3, dtype=int)
np.add.at(z, [0, 0, 1], 1)
print(z) # [2 1 0], add.at accumulates over repeatsUse np.add.at whenever the same position can appear more than once and you need a running total.
Choosing an indexing method
The diagram summarizes which kind of index fits which situation.
The table compares the three approaches.
| Property | Basic slice | Boolean mask | Integer array |
|---|---|---|---|
| Selection defined by | Start, stop, step | A condition per element | Explicit positions |
| Result shares memory with original | Yes (view) | No (copy) | No (copy) |
| Result shape | Depends on slice | 1D for a full-shape mask | Shape of the index array |
| Can repeat or reorder elements | No | No | Yes |
| Assignment writes to original | Yes | Yes | Yes |
Common errors and pitfalls
- Using
andororbetween comparisons raisesValueError: The truth value of an array with more than one element is ambiguous. Use&and|with parentheses. - Assuming that a mask result is a view. Edits to
a[mask]after the selection do not changea. To changea, assign through the mask directly:a[mask] = .... - Chaining two selections and then assigning. In
a[mask][0] = 5, the first step builds a copy and the assignment lands in that temporary copy, soadoes not change. Combine the selection into a single index expression instead. - Expecting
m[[0, 2], [1, 3]]to return a block. It returns the two paired elements. Usenp.ix_for the cross product. - Mask length that does not match its axis, or an index outside the axis, both raise
IndexError. - Expecting
+=to accumulate over repeated positions. Usenp.add.at.
Exercise
Let m = np.arange(12).reshape(3, 4). (a) What does m[[0, 2], [1, 3]] return? (b) Write one expression that returns the 2x2 block made of rows 0 and 2 and columns 1 and 3. (c) Write one statement that sets every odd value in m to -1 in place.
Show answer
(a) It returns the paired elements (0,1) and (2,3), which is the array [1 11]. (b) m[np.ix_([0, 2], [1, 3])] returns [[1 3], [9 11]]. An equivalent form is m[[[0], [2]], [1, 3]]. (c) m[m % 2 == 1] = -1 assigns through a boolean mask, so the original array changes.
Exercise
Given a = np.array([5, 3, 8, 3, 1]), you run a[a > 4][0] = 100. Does a change? Explain, and give a statement that changes the first element greater than 4 in a.
Show answer
No, a does not change. The mask selection a[a > 4] returns a copy, and the assignment writes the 100 into that temporary copy. To change the original, use the position: a[np.flatnonzero(a > 4)[0]] = 100, which sets a[0] to 100 and leaves the other elements as they were.