Array Maths and Broadcasting

Arrays of different shapes can still meet, under one clear rule.

Elementwise by default

Two arrays of the same shape combine position by position. No loop, no zip.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)
print(a * b)

Broadcasting stretches the smaller one

A single number is treated as if repeated to fit. That is why + 5 worked earlier, and the same rule extends to rows and columns.

import numpy as np

prices = np.array([10.0, 20.0, 30.0])
print(prices * 1.08)
print(prices - prices.mean())

Exercise

Try It Yourself

Write centred(values) that returns a list of each value minus the mean of them all, rounded to two decimal places.

Press Run to see output

Check Your Understanding