Sub topic 5
Boolean Masks and Integer-Array Indexing
This chapter assumes you know basic Python, can import NumPy, and have read the earlier chapters on shape, basic slicing, and views versus copies. It covers two ways to select elements by value or by position list, and what each one returns.
Why a second kind of indexing
Basic slicing selects a regular pattern: every row, columns 1 to 3, every second element. It cannot express "all values above 5" or "rows 4, 0 and 2, in that order". NumPy handles these cases with advanced indexing, where the index is itself an array.
There are two forms:
- A boolean mask, an array of
TrueandFalsewith the same shape as the data. - An integer array, which lists positions to pick.
Boolean masks
A comparison on an array produces a boolean array. Using that array as an index keeps the elements where the mask is True.
import numpy as np
a = np.arange(12).reshape(3, 4)
mask = a > 5
print(mask.shape) # (3, 4)
print(a[mask]) # [ 6 7 8 9 10 11]The result is always one-dimensional. NumPy cannot guarantee that each row keeps the same number of elements, so it flattens the selected values in row-major order.
Combine conditions with & (and), | (or) and ~ (not). Wrap each comparison in parentheses, because these operators bind more tightly than comparisons. Python's and and or raise an error on arrays.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[(a > 2) & (a < 7)]) # [3 4 5 6]
print(a[~(a % 2 == 0)]) # [ 1 3 5 7 9 11]A mask can also be used on the left side of an assignment, which modifies the original array in place.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[a > 8] = 0
print(a[2]) # [8 0 0 0]Integer-array indexing
Pass a list or array of integers to pick elements by position. The result follows the order of the index, and repeats are allowed.
import numpy as np
v = np.array([10, 20, 30, 40, 50])
print(v[[4, 0, 2, 2]]) # [50 10 30 30]On a 2-D array, one index array selects whole rows. Two index arrays are paired element by element to pick individual cells.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[[2, 0]]) # rows 2 and 0
print(a[[0, 1, 2], [1, 2, 3]]) # cells (0,1), (1,2), (2,3) -> [ 1 6 11]Negative integers count from the end, as in lists. An integer outside the valid range raises IndexError.
Copies, not views
Unlike basic slices, both forms return a copy. Editing the result does not change the original array.
import numpy as np
a = np.arange(12).reshape(3, 4)
big = a[a > 5]
big[0] = -1
print(a[1, 2]) # 6, unchangedAssignment is the exception in practice. a[mask] = value and a[[0, 2]] = value write into a itself, because Python turns them into a single set-item call on a. Chained forms such as a[mask][0] = 1 do not work: the first step makes a copy, and the write goes to that copy.
Choosing between them
| Need | Use |
|---|---|
| Select by a condition on values | Boolean mask |
| Select specific positions, reorder, or repeat | Integer array |
| Position of each `True` in a mask | `np.nonzero(mask)` or `np.flatnonzero(mask)` |
np.nonzero converts a mask into integer indices, so the two forms are interchangeable.
Exercise
Given a = np.array([4, 9, 2, 7, 5]), write one expression that returns the values greater than 4 in their original order, and another that returns the elements at positions 3, 0 and 3. What are the two results?
Show answer
a[a > 4] gives [9 7 5]. a[[3, 0, 3]] gives [7 4 7]. Both results are copies of the data in a.
Exercise
Why does a[a > 5][0] = -1 leave a unchanged, while a[a > 5] = -1 modifies it?
Show answer
In the first, a[a > 5] runs as a read and returns a copy, and the assignment [0] = -1 is applied to that copy. In the second, the whole statement is one set-item call on a, so NumPy writes -1 into the selected positions of a.