typestar

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

  1. grid[0, 0] and grid[:, -1] slice by position.
  2. A boolean mask like grid[grid % 2 == 0] filters.
  3. Assigning through a mask edits in place.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Arrays, step 2 of 22 in NumPy.

← Previous Next →