Fancy indexing
Pass a list of positions to pick several elements in any order at once.
In this page:
Syntax
arr[[index1, index2, index3]]
matrix[[row1, row2], [col1, col2]]
Fancy indexing
Indexing with an integer array or list selects those exact positions, in the order given, and repeats are allowed. On 2-D arrays, two index arrays pick matching row and column pairs. Fancy indexing returns a copy.
Note:
Use it to reorder rows: m[[2, 0, 1]].
Example: Fancy indexing
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[[0, 2, 4]])
print(a[[4, 4, 0]])
m = np.arange(9).reshape(3, 3)
print(m[[0, 1, 2], [2, 1, 0]])
# Output:
# [10 30 50]
# [50 50 10]
# [2 4 6]
Related Topics
Common Mistakes
- Expecting a view instead of a copy
- Passing a tuple where a list is needed
- Mismatched index array lengths
Chapter Summary
- Index with lists or arrays of ints
- Order and repeats are preserved
- Returns a copy
- Paired arrays select cells on 2-D arrays
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: