Sub topic 7
Boolean Masks and Fancy Indexing
This chapter assumes you can create arrays, read shape and dtype, and use basic slicing. It also assumes you know that a basic slice returns a view. Here you will learn the two kinds of "advanced" indexing: boolean masks and integer-array (fancy) indexing. You will see how they differ from slices, where they surprise people, and how to use them for selection and assignment.
Why advanced indexing is different
Basic slicing, such as a[1:4], describes a regular pattern: a start, a stop, and a step. NumPy can express that pattern as an offset plus strides, so it returns a view of the same memory.
Boolean masks and integer arrays select elements that may have no regular pattern. NumPy cannot describe a[[4, 0, 2]] as one start and one stride. It therefore gathers the elements into new memory. This leads to the main rule of the chapter:
- Reading with a mask or an integer array returns a copy.
- Assigning through a mask or an integer array writes into the original array.
The next sections show both sides of that rule.
Boolean masks
A boolean mask is an array of True and False values. Comparisons on arrays produce one, element by element.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
mask = a > 0
print(mask) # [ True False True False True]
print(a[mask]) # [3 4 9]
print(a[a > 0]) # [3 4 9], same thing without a nameIndexing with a mask keeps the elements where the mask is True. The mask must have the same shape as the array, or at least match the axes it indexes. The result of a[mask] is always one-dimensional when the mask covers every axis of a, because the surviving elements no longer form a rectangle.
import numpy as np
m = np.array([[1, -2, 3],
[-4, 5, -6]])
print(m[m > 0]) # [1 3 5]
print(m[m > 0].shape) # (3,)Combining conditions
Python's and, or, and not do not work on arrays. They try to reduce the whole array to a single truth value and raise a ValueError. Use the elementwise operators &, |, and ~, and put parentheses around each comparison. The operators & and | bind more tightly than > or ==, so without parentheses the expression is evaluated in the wrong order.
import numpy as np
a = np.array([3, -1, 4, -5, 9, 12])
print(a[(a > 0) & (a < 10)]) # [3 4 9]
print(a[(a < 0) | (a > 10)]) # [-1 -5 12]
print(a[~(a > 0)]) # [-1 -5]Assigning through a mask
Placing a mask on the left side of an assignment modifies the original array in place.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
a[a < 0] = 0
print(a) # [3 0 4 0 9]You can assign a single value, which is broadcast to every selected position. You can also assign an array whose length equals the number of selected elements.
import numpy as np
a = np.array([10, 20, 30, 40])
a[a > 15] = [1, 2, 3]
print(a) # [10 1 2 3]Counting and testing with masks
Because True counts as 1, reductions on a mask answer common questions without building the filtered array.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
print((a > 0).sum()) # 3, how many positives
print((a > 0).mean()) # 0.6, fraction of positives
print((a > 5).any()) # True
print((a > 0).all()) # FalseInteger-array (fancy) indexing
Fancy indexing selects elements by passing a list or array of integer positions. The result follows the order and repetition in the index, not the order in the source.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[[0, 2]]) # [10 30]
print(a[[4, 0, 0, 2]]) # [50 10 10 30]
print(a[[-1, -2]]) # [50 40], negative positions workThe shape of the result is the shape of the index array, not the shape of the source. This lets you build a 2-D result from a 1-D source.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
idx = np.array([[0, 1], [3, 4]])
print(a[idx])
# [[10 20]
# [40 50]]Indexing several axes at once
When you give one integer array per axis, NumPy pairs them up element by element. It does not form a grid.
import numpy as np
m = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
rows = np.array([0, 1, 2])
cols = np.array([3, 0, 1])
print(m[rows, cols]) # [3 4 9], picks (0,3), (1,0), (2,1)If you want whole rows, index only the first axis. If you want a rectangular block of chosen rows and columns, turn the row index into a column vector so that the two indices broadcast against each other.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[[0, 2]]) # rows 0 and 2
print(m[[0, 2], :][:, [1, 3]]) # [[ 1 3]
# [ 9 11]]
print(m[np.ix_([0, 2], [1, 3])]) # same block, in one step
print(m[[[0], [2]], [1, 3]]) # same block via broadcastingnp.ix_ is the clearest way to get the "grid" behavior.
Fancy assignment and repeated indices
Assignment through an integer array writes to the original. If the same position appears more than once, only the last write is kept.
import numpy as np
a = np.zeros(4, dtype=np.int64)
a[[1, 1, 2]] = [5, 6, 7]
print(a) # [0 6 7 0]Augmented assignment is a trap here. a[idx] += 1 reads, adds, then writes, so repeated positions are incremented once, not once per repeat. Use np.add.at to accumulate correctly.
import numpy as np
a = np.zeros(4, dtype=np.int64)
idx = [1, 1, 2]
a[idx] += 1
print(a) # [0 1 1 0], position 1 incremented once
b = np.zeros(4, dtype=np.int64)
np.add.at(b, idx, 1)
print(b) # [0 2 1 0]Mixing slices, masks, and integers
You can combine indexing styles in one expression. A slice on one axis keeps that axis as a view-like selection, while the array index on another axis forces a gather. The whole result is still a copy.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m[:, [0, 3]]) # all rows, columns 0 and 3
print(m[m[:, 0] > 0]) # rows whose first element is positiveThe second line uses a one-dimensional mask on the first axis to select whole rows. This is a common way to filter a table by a condition on one column.
Views, copies, and chained indexing
Reading with a mask or an integer array gives a copy. This explains a frequent bug: chained indexing.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
a[a > 0][0] = 100 # modifies a temporary copy
print(a) # [ 3 -1 4 -5 9], unchanged
a[np.where(a > 0)[0][0]] = 100 # one index operation on a
print(a) # [100 -1 4 -5 9]The first form runs a[a > 0], which makes a new array, and then assigns into that temporary. The original never changes. Keep the assignment in a single indexing expression, such as a[mask] = value.
Useful helpers
np.where(cond)returns the integer positions wherecondisTrue, as a tuple with one array per axis.np.where(cond, x, y)picks fromxwherecondisTrueand fromyelsewhere. It returns a new array and leaves the source unchanged.np.nonzero(mask)behaves like the one-argumentnp.where.np.take(a, idx)is a function form of fancy indexing on one axis.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
print(np.where(a > 0)) # (array([0, 2, 4]),)
print(np.where(a > 0, a, 0)) # [3 0 4 0 9]
print(np.where(a > 0, "pos", "neg")) # ['pos' 'neg' 'pos' 'neg' 'pos']Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: truth value of an array is ambiguous` | Used `and`, `or`, or a chained comparison like `0 < a < 10` | Use `(a > 0) & (a < 10)` |
| `IndexError: boolean index did not match` | Mask length differs from the axis length | Build the mask from the same array or axis |
| `IndexError: index 7 is out of bounds` | Integer index beyond the axis size | Check `a.shape` and the index values |
| Assignment seems to do nothing | Assigned into the copy returned by a chained index | Use one expression: `a[mask] = value` |
| Counts wrong after `a[idx] += 1` | Repeated indices are applied once | Use `np.add.at` |
| Result has an unexpected shape | Two index arrays were paired, not crossed | Use `np.ix_` or broadcast the indices |
Performance notes
Masks and fancy indexing are vectorized, so they are much faster than a Python loop that tests each element. They do cost memory, since a mask holds one byte per element and a gather allocates a new array. For a very large array, a repeated chain of filters creates several temporary arrays. Build one combined mask instead, and apply it once.
Fancy indexing is also slower than a slice of the same size, because it copies and cannot use a simple stride. If you only need a regular pattern, such as every second element, prefer a[::2].
Exercise
Given a = np.array([5, 12, 7, 20, 3, 15]), write a single statement that sets every value greater than 10 and less than 18 to 0, and give the resulting array. Then explain why a[a > 10][0] = 0 would not have achieved this.
Show answer
Use a[(a > 10) & (a < 18)] = 0. The matching values are 12 and 15, so the result is [ 5 0 7 20 3 0]. The expression a[a > 10] is a read with a boolean mask, which returns a copy. The [0] = 0 then assigns into that temporary copy, so a is never modified. The assignment must appear in the same indexing expression applied to a.
Exercise
Let a = np.zeros(3, dtype=np.int64) and idx = [0, 0, 2, 2, 2]. What does a[idx] += 1 leave in a, and what code gives the count of how many times each position appears?
Show answer
a[idx] += 1 leaves [1 0 1], because each position is read once, incremented once, and written back, so repeats collapse. To count occurrences, use np.add.at(a, idx, 1), which gives [2 0 3].