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
- No axis reduces the whole array.
axis=1collapses columns;axis=0collapses rows.argmaxandcumsumlocate and accumulate.
Keywords and builtins used here
as
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.
Step 2 of 4 in Math & shapes, step 4 of 22 in NumPy.