Skip to content
AI-grafen
DAI developerProgramming· about 45 min· fundamentals that rarely change· verified 2026-09-20· EN

NumPy — arrays and vectorisation

Be able to create and compute with arrays, broadcasting and axes without Python loops.

Prerequisites

Intuition

NumPy gives you arrays: grids of numbers with a fixed type, stored contiguously in memory. Two things follow from that:

  1. Vectorisation — a + b adds whole arrays in C code instead of a Python loop. Often 50–100 times faster.
  2. 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

All the sources and licences