Skip to content

NumPy

Broadcasting

8 min+75 XPStep 1/10

Stretch the small one to fit

What happens when shapes don't match? a + 10 adds ten to every element — NumPy broadcasts the scalar across the whole array, no copying, no loop.

The rule, comparing shapes right-to-left: dimensions are compatible when they're equal, or one of them is 1, or missing entirely. So (4, 3) + (3,) works — the row vector is stretched across all 4 rows — while (4, 3) + (4,) errors out.

This is why preprocessing is a one-liner:

  • prices - prices.mean() — center a column
  • X - X.mean(axis=0) — center every column of a matrix at once
  • (X - X.mean(axis=0)) / X.std(axis=0) — full z-score standardization in a single expression

insight

Broadcasting is how a vector of column means gets subtracted from every row of a dataset. 'Pretend the small array is tiled to match the big one' is the whole mental model.