NumPy — arrays and vectorisation
Be able to create and compute with arrays, broadcasting and axes without Python loops.
Prerequisites
- CPython — lists, loops and dictionariesrequired
- DVectorsrequiredPractise in Mattegrafen ↗
Intuition
NumPy gives you arrays: grids of numbers with a fixed type, stored contiguously in memory. Two things follow from that:
- Vectorisation —
a + badds whole arrays in C code instead of a Python loop. Often 50–100 times faster. - Broadcasting — arrays of different shapes can be combined if the shapes are compatible: a (3, 4) array plus a (4,) array adds the row to every row.
Axes are what confuses people most: axis=0 goes downwards (over the rows → one value per column), axis=1 goes rightwards (over the columns → one value per row).
Code
import numpy as np
X = np.arange(12).reshape(3, 4)
print(X)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(X.sum(axis=0)) # [12 15 18 21] one value per column
print(X.sum(axis=1)) # [ 6 22 38] one value per row
print(X.shape, X.dtype) # (3, 4) int64
# broadcasting: (3,4) + (4,) → the row is added to every row
print(X + np.array([100, 200, 300, 400]))
# standardise column by column — the basis of feature scaling
Xs = (X - X.mean(axis=0)) / X.std(axis=0)
print(np.round(Xs.mean(axis=0), 6)) # [0. 0. 0. 0.]
# masking instead of a loop plus an if
print(X[X % 2 == 0]) # [ 0 2 4 6 8 10]
The trap: X.mean(axis=0) gives shape (4,) — if you want to keep the dimension for broadcasting back, use keepdims=True.
Mastery means
- Creates arrays and computes without Python loops
- Uses axes and broadcasting correctly
- Explains why vectorisation is faster
Sign in to do the exercises and build your mastery up.
Sources
- NumPy — dokumentation (BSD-3) — BSD-3-Clause
Leads to
Part of the goals (11)
- The developer's toolbox
- Image classification with convolutional networks
- Training neural networks for real
- Classical machine learning in practice
- Systems knowledge for AI engineers
- Classical ML for real
- Data: collect, clean, document
- Multimodal systems
- Generative models in depth
- Build a RAG system you can trust
- AI in production