Skip to main content
Albero Academy

Aggregations & Axes

Summarise arrays with sum, mean and friends, control the axis, generate random data, and touch linear algebra.

Chapter 4NumPy15 min readBeginner friendly
  • #NumPy
  • #Aggregations
  • #Axis

The last piece is boiling arrays down to numbers — totals, averages, maxima — and doing it along the right dimension. The axis argument trips up every beginner exactly once; after this chapter it won't trip up you.

Aggregations

summarising
a = np.array([3, 1, 4, 1, 5, 9])
a.sum() # 23
a.mean() # 3.83…
a.min() # 1
a.max() # 9
a.std() # standard deviation
a.argmax() # 5 (index of the max)
np.median(a) # 3.5

The axis argument

On a 2-D array, an aggregation collapses a whole dimension. axis=0 collapses the rows (giving a result per column); axis=1 collapses the columns (a result per row):

axis=0 vs axis=1
m = np.array([[1, 2, 3],
[4, 5, 6]])
m.sum() # 21 everything
m.sum(axis=0) # [5 7 9] down each column
m.sum(axis=1) # [6 15] across each row
m.mean(axis=0) # [2.5 3.5 4.5] column averages

Random & reproducibility

Generate random data for simulations and sampling — and seed the generator so results are reproducible:

random data
rng = np.random.default_rng(42) # seed → same numbers every run
rng.random(3) # 3 floats in [0, 1)
rng.integers(1, 7, size=10) # 10 dice rolls
rng.normal(loc=0, scale=1, size=5)# 5 samples from a normal distribution
rng.choice(["A", "B", "C"], size=4)

A taste of linear algebra

NumPy handles vectors and matrices directly — the maths behind machine learning:

matrix maths
A = np.array([[1, 2], [3, 4]])
v = np.array([1, 0])
A @ v # matrix–vector product → [1 3]
A @ A # matrix product
np.linalg.inv(A) # inverse
A.T # transpose

Practice

Make a 5×3 array of random exam scores. Compute each student's average (across subjects) and each subject's average (across students) — choosing the right axis for each. Find the index of the top-scoring student with argmax.

Key takeaways

  1. 01Aggregations (sum, mean, min, max, std, argmax) reduce an array to summary numbers.
  2. 02axis=0 collapses rows → a result per column; axis=1 collapses columns → a result per row.
  3. 03Use np.random.default_rng(seed) for reproducible random data.
  4. 04NumPy does linear algebra: @ for matrix products, np.linalg for inverse/solve, .T for transpose.
  5. 05These four chapters — arrays, indexing, vectorization, aggregation — are the base pandas builds on.