Lesson 07
Advanced Indexing
Pick scattered values with index lists: chosen positions in 1-D, row and column pairs in 2-D, sub-grids with ix_, and positions in 3-D arrays.
A slice can only take evenly spaced positions. To pick scattered values, pass a list or an array of indices instead. This is called advanced, or fancy, indexing. It always returns a new array.
1-D: a list of positions
Put the positions in a list, or in an ndarray, and pass it inside the brackets. Positions can repeat and can be negative.
import numpy as np
a = np.array([40, 15, 72, 8, 63, 27, 90, 51])
print(a[[0, 3, 7]])
picks = np.array([0, -2, -1])
print(a[picks])
print(a[[2, 2, 0]])Output:
[40 8 51]
[40 90 51]
[72 72 40]2-D: row and column pairs
m[rows, cols] with two lists reads them as pairs. The first row goes with the first column, the second row with the second column. Tuples work the same way as lists.
import numpy as np
m = np.array([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]])
print(m[[0, 2], [1, 3]])
print(m[(0, 1, 2), (0, 1, 2)])Output:
[12 34]
[11 22 33]Whole rows and sub-grids
One list picks whole rows, in the order you give. To keep every combination of chosen rows and chosen columns, wrap both lists in np.ix_.
import numpy as np
m = np.array([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]])
print(m[[2, 0]])
print(m[np.ix_([0, 2], [1, 3])])Output:
[[31 32 33 34]
[11 12 13 14]]
[[12 14]
[32 34]]3-D positions
Give one list for blocks, one for rows, and one for columns. Each position reads one value from the lists at the same place.
import numpy as np
t = np.arange(1, 19).reshape(2, 3, 3)
print(t[[0, 1], [1, 2], [2, 0]])Output:
[ 6 16]The result is a copy
Unlike a slice, advanced indexing builds a new array. Changing the result leaves the original alone.
import numpy as np
a = np.array([5, 6, 7, 8])
picked = a[[0, 1]]
picked[0] = -1
print(picked)
print(a)Output:
[-1 6]
[5 6 7 8]Key takeaways
-
Pass a list of positions to pick scattered values
-
Two lists in 2-D are read as row and column pairs
-
np.ix_keeps every chosen row and column combination -
Advanced indexing returns a copy
-
Next: Copy and View
-
Previous: Slicing
Loading playground…
Check your understanding
Advanced Indexing Quiz
What does np.array([5, 6, 7])[[0, 2]] give?
1 / 10