Sub topic 9
Fancy Indexing with Integer Arrays
Fancy indexing means indexing an array with another array (or list) of integers. Slices select regular, evenly spaced regions. Fancy indexing selects arbitrary positions, in any order, with repeats allowed.
This chapter assumes you can create arrays with np.array, np.arange, and reshape. It also assumes you know what shape and dtype mean, and that you have seen basic slicing and the view-versus-copy distinction from earlier chapters.
The basic idea
Put a list or an integer array inside the square brackets. NumPy returns the elements at those positions.
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[[0, 2, 5]]) # [10 30 60]
print(a[[5, 0, 0, -1]]) # [60 10 10 60]
idx = np.array([[0, 1], [4, 5]])
print(a[idx]) # [[10 20]
# [50 60]]Three rules follow from this example:
- The order of the result follows the order of the indices, not the order of the array.
- Indices may repeat, so one source element can appear several times in the result.
- Negative indices count from the end, as they do with single integers.
The shape of the result is the shape of the index array. A 2-D index array over a 1-D source gives a 2-D result. This is a common way to build lookup tables: the index array holds codes and the source array holds the values those codes stand for.
Fancy indexing always copies
A basic slice returns a view that shares memory with the original. Fancy indexing returns a new array with its own memory.
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
b = a[[0, 1]]
b[0] = -1
print(a[0]) # 10, a is unchanged
print(np.shares_memory(a, b)) # False
s = a[0:2]
print(np.shares_memory(a, s)) # TrueThe copy has a cost. Selecting a million positions allocates a million-element array. A slice would allocate nothing. When the positions are regular, for example every second element, a slice is both faster and lighter on memory.
The exception is assignment. When the fancy index appears on the left side of =, NumPy writes into the original array. The copying rule applies only when you read.
import numpy as np
x = np.zeros(5, dtype=int)
x[[1, 3]] = [7, 9]
print(x) # [0 7 0 9 0]Indexing rows and columns of 2-D arrays
With one index array on a 2-D array, you select whole rows.
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[:, [0, 3]]) # [[ 0 3]
# [ 4 7]
# [ 8 11]]The second line mixes a slice with a list. The slice : keeps every row, and the list picks columns 0 and 3. This is the usual way to select columns by position.
Two index arrays are paired, not crossed
With one index array per axis, NumPy pairs them element by element.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[[0, 2], [1, 3]]) # [ 1 11]The result has two elements: a[0, 1] and a[2, 3]. It does not select the 2 by 2 block of rows 0 and 2 crossed with columns 1 and 3. New users often expect that block. To get it, give the index arrays shapes that broadcast against each other:
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = np.array([[0], [2]]) # shape (2, 1)
cols = np.array([1, 3]) # shape (2,)
print(a[rows, cols]) # [[ 1 3]
# [ 9 11]]The shapes (2, 1) and (2,) broadcast to (2, 2), and every row index meets every column index. np.ix_ builds these shaped arrays for you, and a later chapter covers it.
If the index arrays cannot be broadcast together, NumPy raises an error:
import numpy as np
a = np.arange(12).reshape(3, 4)
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,)Common uses
Reordering by another array
np.argsort returns the integer positions that would sort an array. Using those positions as a fancy index reorders a second array to match.
import numpy as np
scores = np.array([72, 95, 60, 88])
names = np.array(["Ana", "Ben", "Cy", "Dee"])
order = np.argsort(scores)[::-1]
print(order) # [1 3 0 2]
print(names[order]) # ['Ben' 'Dee' 'Ana' 'Cy']
print(scores[order]) # [95 88 72 60]Converting a mask to positions
A boolean mask says which elements match. np.flatnonzero turns the mask into the integer positions of the True entries. You need positions when you want to know where the matches are, or when you want to apply the same selection to several arrays.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
pos = np.flatnonzero(data > 1)
print(pos) # [0 2 5]
print(data[pos]) # [4 7 2]Sampling and shuffling
An index array drawn at random gives you a random sample or a shuffled order. Drawing with repeats allowed gives a bootstrap-style sample.
import numpy as np
rng = np.random.default_rng(0)
data = np.arange(100, 110)
pick = rng.integers(0, len(data), size=4) # repeats are possible
sample = data[pick]
print(sample.shape) # (4,)Assignment gotchas
Repeated indices in a plain assignment
If an index repeats in an assignment, more than one value is written to the same slot. NumPy does not promise which one wins in every case, but in practice the last value is the one that remains.
import numpy as np
x = np.zeros(3, dtype=int)
x[[0, 0, 0]] = [1, 2, 3]
print(x) # [3 0 0]Do not build logic on this. If your indices can repeat, treat the outcome as undefined.
Repeated indices with `+=`
This is the most common surprise. x[idx] += 1 reads the selected elements once, adds 1 to the copy, and writes the results back. If an index repeats, the increments do not stack.
import numpy as np
counts = np.zeros(4, dtype=int)
counts[[1, 1, 2]] += 1
print(counts) # [0 1 1 0], not [0 2 1 0]
counts2 = np.zeros(4, dtype=int)
np.add.at(counts2, [1, 1, 2], 1)
print(counts2) # [0 2 1 0]np.add.at applies the operation once for every index, including repeats. np.bincount is a faster option for plain counting of non-negative integers.
Bounds, dtype, and alternatives
Out-of-range indices raise an IndexError. NumPy does not clip or wrap them silently.
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
try:
a[[0, 6]]
except IndexError as e:
print(e) # index 6 is out of bounds for axis 0 with size 6Index arrays must hold integers or booleans. A float array raises an IndexError, even if every value is a whole number such as 2.0. If your indices came out of a calculation as floats, convert them with .astype(int) first.
A list of booleans is treated as a mask, not as the integers 0 and 1. a[[True, False]] and a[[1, 0]] mean different things, so check the dtype when a result looks wrong.
np.take does the same job as fancy indexing on one axis, and it can handle out-of-range positions through its mode argument:
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(np.take(a, [1, 7], mode="wrap")) # [20 20]
print(np.take(a, [1, 7], mode="clip")) # [20 60]With mode="wrap", index 7 becomes 7 modulo 6, which is 1. With mode="clip", it becomes the last valid index, 5.
Summary of behavior
| Expression | Selects | Result shape | View or copy |
|---|---|---|---|
| `a[[0, 2, 5]]` | Elements at those positions | Shape of the index list | Copy |
| `a[idx2d]` on a 1-D array | Elements, arranged like `idx2d` | Shape of `idx2d` | Copy |
| `a[[2, 0]]` on a 2-D array | Whole rows, in that order | `(2, ncols)` | Copy |
| `a[:, [0, 3]]` | Chosen columns, all rows | `(nrows, 2)` | Copy |
| `a[[0, 2], [1, 3]]` | Paired elements `(0,1)` and `(2,3)` | `(2,)` | Copy |
| `a[[0, 2], [1, 3]] = v` | Writes to those elements | Not applicable | Writes into `a` |
Exercises
Exercise
Given a = np.arange(12).reshape(3, 4), what does a[[0, 2], [1, 3]] return, and how would you get the 2 by 2 block made of rows 0 and 2 and columns 1 and 3 instead?
Show answer
It returns [1 11], the elements a[0, 1] and a[2, 3], because the two index lists are paired. For the block, use index arrays that broadcast, such as a[np.array([[0], [2]]), np.array([1, 3])], which gives [[1 3] [9 11]].
Exercise
You run counts = np.zeros(4, dtype=int) and then counts[[1, 1, 2]] += 1. What does counts contain, and what call gives the answer [0 2 1 0]?
Show answer
counts is [0 1 1 0], because the read-add-write happens once and the repeated index 1 is written twice with the same value. np.add.at(counts, [1, 1, 2], 1) applied to a fresh zero array gives [0 2 1 0].
Exercise
b = a[[0, 1]] and s = a[0:2] select the same two elements of a 1-D array a. You then set b[0] = -1 and s[0] = -2. Which assignment changes a, and why?
Show answer
Only s[0] = -2 changes a. The slice s is a view that shares memory with a, while b is a copy created by fancy indexing.