Fancy indexing in Python
Indexing with arrays of positions, which copies rather than views.
import numpy as np
grid = np.arange(20).reshape(4, 5)
print(grid[[0, 3, 0]])
print(grid[[0, 1, 2], [4, 3, 2]])
scores = np.array([88, 104, 91, 79])
order = np.argsort(scores)[::-1]
print(order, scores[order])
print(np.argmax(scores), np.argmin(scores))
How it works
- An integer array picks rows in any order, repeats allowed.
- Two index arrays pick individual elements pairwise.
argsortgives the permutation that would sort the array.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 11
- Characters to type
- 255
- Tokens
- 108
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 62 seconds.
Step 2 of 3 in Indexing, step 14 of 22 in NumPy.