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
a = np.array([3, 1, 4, 1, 5, 9])a.sum() # 23a.mean() # 3.83…a.min() # 1a.max() # 9a.std() # standard deviationa.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):
m = np.array([[1, 2, 3],[4, 5, 6]])m.sum() # 21 everythingm.sum(axis=0) # [5 7 9] down each columnm.sum(axis=1) # [6 15] across each rowm.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:
rng = np.random.default_rng(42) # seed → same numbers every runrng.random(3) # 3 floats in [0, 1)rng.integers(1, 7, size=10) # 10 dice rollsrng.normal(loc=0, scale=1, size=5)# 5 samples from a normal distributionrng.choice(["A", "B", "C"], size=4)
A taste of linear algebra
NumPy handles vectors and matrices directly — the maths behind machine learning:
A = np.array([[1, 2], [3, 4]])v = np.array([1, 0])A @ v # matrix–vector product → [1 3]A @ A # matrix productnp.linalg.inv(A) # inverseA.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
- 01Aggregations (sum, mean, min, max, std, argmax) reduce an array to summary numbers.
- 02axis=0 collapses rows → a result per column; axis=1 collapses columns → a result per row.
- 03Use np.random.default_rng(seed) for reproducible random data.
- 04NumPy does linear algebra: @ for matrix products, np.linalg for inverse/solve, .T for transpose.
- 05These four chapters — arrays, indexing, vectorization, aggregation — are the base pandas builds on.
