Lesson 4 / 25

Aggregation and Random Numbers

Summaries along axes, seeded generators.

sum, mean, argmax, percentile, default_rng

Reductions such as sum, mean, std, max, argmax and percentile work over the whole array or along an axis. For random numbers, create a Generator with np.random.default_rng(seed): it is the modern API, and a fixed seed makes simulations, sampling and tests reproducible. Pass the generator around instead of relying on global random state.

Statistics, randomness and precision

Aggregations, reproducible random numbers and floating-point awareness make NumPy results trustworthy.

Three ideas: aggregation and randomness, floating point, vectorisation.
Figure 2.1 — Aggregates, floats and vectorisation.

Exam statistics with a seeded generator, run

I ran this with Python 3.12.3 and NumPy 2.5.3. With seed 42 the same 4 by 3 score matrix appears every run: the mean per exam, the best score per student, the top student by total, and the 90th percentile.

import numpy as np

rng = np.random.default_rng(seed=42)
scores = rng.integers(40, 100, size=(4, 3))   # 4 students x 3 exams
print(scores)
print("overall mean:", scores.mean().round(2))
print("per exam    :", scores.mean(axis=0).round(2))
print("per student :", scores.max(axis=1))
print("best student:", scores.sum(axis=1).argmax())
print("percentile 90:", np.percentile(scores, 90))
print(rng.normal(0, 1, size=3).round(3))

Output:

[[45 86 79]
 [66 65 91]
 [45 81 52]
 [45 71 98]]
overall mean: 68.67
per exam    : [50.25 75.75 80.  ]
per student : [86 91 81 98]
best student: 1
percentile 90: 90.5
[ 0.128 -0.316 -0.017]

Seed experiments, not production randomness

Fixed seeds are for reproducible analysis and tests; never use them for security tokens (use the secrets module).

Quick check: What does scores.mean(axis=0) return for a students-by-exams matrix?

  • The mean of each student (row)
  • The mean of each exam (column)
  • A single overall mean
  • The median
Answer

The mean of each exam (column) — axis=0 collapses rows.