Start studying
Module 6 · Data Wrangling Module contents
Module 6  ·  Card 6 / 14advanced

Array Broadcasting

Broadcasting is how NumPy combines arrays of different shapes in one operation.

The smaller array is treated as if it were repeated to fit the larger one, without copying any data.

For example, subtracting each city's average from a 10 by 168 temperature array uses an array of shape 10 by 1.

Shapes are compared from the last dimension backwards, and each pair of sizes must be equal or include a 1.

Broadcasting removes loops, but shapes that fit by accident can give a wrong result with no error.

Learn in depth ↓
Module 06 · Data Wrangling · 14 concepts
In depth  /  15 lines

Array Broadcasting, in more detail

Without broadcasting, combining arrays of different shapes would need loops or copies.

Adding a single number to an array is the simplest case: the number is applied to every element.

The broadcasting rules extend that idea to whole rows and columns.

NumPy lines the two shapes up from the right, last dimension first.

If one array has fewer dimensions, sizes of 1 are added to the front of its shape.

Each pair of sizes must then be equal, or one of them must be 1.

A size of 1 is stretched to match the other, and the result takes the larger size in each position.

So shapes (10, 168) and (168,) work, applying one value per hour to every city.

Shapes (10, 168) and (10,) fail, because the 10 is compared with 168.

Reshaping the second array to (10, 1) fixes it, by putting the 10 in the row position.

No data is copied while stretching, so broadcasting is fast and light on memory.

The risk is a silent mismatch: arrays of shape (5, 1) and (5,) combine into a 5 by 5 grid instead of 5 values.

Checking the shape before and after an operation catches most of these mistakes.

Broadcasting is used constantly in practice, for centring columns, converting units and computing distances.

The common misconception is that NumPy repeats any smaller array to fit; it only stretches sizes of 1.

Test yourself

One question on this card. Every option explains itself once you pick, right or wrong.

Question 1
An array has shape 10 by 168. Which second array can be subtracted from it directly through broadcasting?
Data Wrangling

14 concepts in this module, then a graded test with every answer explained.

Study this module →
↑↓ move↵ openesc close