typestar

Aggregation over axes in Python

Reducing arrays with mean, sum, and friends per axis.

import numpy as np

scores = np.array([[85, 90, 78], [72, 88, 95], [60, 70, 80]])

overall = scores.mean()
per_student = scores.mean(axis=1)
per_test = scores.max(axis=0)
spread = scores.std()

total = scores.sum()
best_index = scores.argmax()
running = scores.cumsum(axis=1)

How it works

  1. No axis reduces the whole array.
  2. axis=1 collapses columns; axis=0 collapses rows.
  3. argmax and cumsum locate and accumulate.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
275
Tokens
94
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 4 in Math & shapes, step 4 of 22 in NumPy.

← Previous Next →