Sub topic 9
Fancy indexing with integer arrays
This chapter assumes you can create arrays with np.arange and reshape, read an array's shape, and use integer indices and slices on one- and two-dimensional arrays. It also assumes you know that a basic slice is a view of the original array.
What fancy indexing is
Fancy indexing means indexing with a list or array of integers instead of a single integer or a slice. You use it to pick elements in any order, including repeats, which a slice can't do.
import numpy as np
a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a[[2, 0]]) # [[ 8 9 10 11]
# [ 0 1 2 3]]
print(a[[1, 1, 0]]) # row 1 twice, then row 0
print(a[[-1, 0]]) # negative indices work tooAn index array on the first axis selects whole rows, in the order you list them. To select columns, put the index array in the second position and a bare : in the first.
print(a[:, [0, 3]]) # [[ 0 3]
# [ 4 7]
# [ 8 11]]Result shape follows the index array
The result takes its shape from the index array, and the axes you did not index are kept. If the index array is two-dimensional, the result gains those dimensions.
idx = np.array([[0, 1],
[2, 0]])
out = a[idx]
print(idx.shape, out.shape) # (2, 2) (2, 2, 4)Each integer in idx was replaced by the whole row it names, so the result has shape (2, 2) for the index and 4 for the row.
Pairing index arrays
When you give one index array per axis, NumPy pairs them element by element. It does not build a grid.
print(a[[0, 2], [1, 3]]) # [ 1 11], elements (0, 1) and (2, 3)The arrays must have the same shape, or be broadcastable against each other. If they aren't, NumPy raises an error.
try:
a[[0, 1, 2], [0, 1]]
except IndexError as e:
print(e) # shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)To select every combination of some rows and some columns, use np.ix_, which a later chapter covers.
Fancy indexing returns a copy
Unlike a basic slice, fancy indexing always copies the data. Writing to the result does not change the original.
b = np.arange(12).reshape(3, 4)
rows = b[[0, 1]]
rows[0, 0] = -5
print(b[0, 0]) # 0, unchanged
print(np.shares_memory(b, rows)) # FalseAssigning through integer arrays
On the left side of an assignment, fancy indexing writes into the original array.
x = np.zeros(5, dtype=int)
x[[1, 3]] = [10, 20]
print(x) # [ 0 10 0 20 0]
x[[0, 0, 2]] = [1, 2, 3]
print(x) # [ 2 10 3 20 0], the last write to index 0 winsRepeated indices matter with augmented assignment. x[idx] += 1 reads the values, adds 1, and writes them back. A repeated index is therefore incremented only once.
c = np.zeros(3, dtype=int)
c[[0, 0, 1]] += 1
print(c) # [1 1 0], not [2 1 0]If you need to count repeats, use np.add.at(c, [0, 0, 1], 1), which gives [2 1 0].
Mixing with slices
You can combine an index array on one axis with a slice on another. The slice axes are kept as they are.
print(a[0:2, [0, 3]]) # [[0 3]
# [4 7]]Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `IndexError: index 3 is out of bounds for axis 0 with size 3` | An integer in the array is too large | Check values against `a.shape` |
| `IndexError: shape mismatch` | Index arrays on different axes can't be broadcast | Make the lengths equal, or use `np.ix_` |
| Original array unchanged after a write | You wrote to a fancy-indexed result, which is a copy | Assign directly: `a[idx] = value` |
| Counts are too low | Repeated indices in `+=` | Use `np.add.at` |
Exercise
Given a = np.arange(12).reshape(3, 4), what does a[[0, 2], [1, 3]] return, and what does a[[0, 2]][:, [1, 3]] return? Why do they differ?
Show answer
The first returns the 1-D array [1 11], because the two index arrays are paired as the points (0, 1) and (2, 3). The second first selects rows 0 and 2, then selects columns 1 and 3 from that result. It returns [[1 3], [9 11]], a 2-D block. The second form gives every row and column combination, and the first gives only the paired points.
Exercise
Let c = np.zeros(4, dtype=int). After c[[1, 1, 3]] += 5, what is c? How would you get [0 10 0 5]?
Show answer
c is [0 5 0 5], because the repeated index 1 is incremented only once. To count repeats, use np.add.at(c, [1, 1, 3], 5), which gives [0 10 0 5].