typestar

The axis argument in Python

axis=0 walks down the rows, axis=1 across the columns.

import numpy as np

grid = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])

print(grid.sum(), grid.sum(axis=0), grid.sum(axis=1))
print(grid.mean(axis=1, keepdims=True))
print(grid / grid.sum(axis=1, keepdims=True))
print(grid.argmax(axis=0))

How it works

  1. An aggregate over axis 0 gives one value per column.
  2. keepdims=True preserves the rank, which broadcasting likes.
  3. Leaving axis out reduces the whole array.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
239
Tokens
97
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 3 of 3 in Indexing, step 15 of 22 in NumPy.

← Previous Next →