Array indexing in Python
Slicing, fancy indexing, and boolean masks.
import numpy as np
grid = np.arange(1, 13).reshape(3, 4)
top_left = grid[0, 0]
first_row = grid[0]
last_col = grid[:, -1]
block = grid[0:2, 1:3]
evens = grid[grid % 2 == 0]
grid[grid > 10] = 0
picked = grid[[0, 2], :]
How it works
grid[0, 0]andgrid[:, -1]slice by position.- A boolean mask like
grid[grid % 2 == 0]filters. - Assigning through a mask edits in place.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 13
- Characters to type
- 221
- Tokens
- 86
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 49 seconds.
Step 2 of 2 in Arrays, step 2 of 22 in NumPy.