NumPy Broadcasting
You have already seen array * 2 multiply every element by 2. NumPy didn't need a second array of 2s: it broadcast the scalar to the array's shape. Broadcasting is the set of rules NumPy uses to combine arrays of different shapes in element-wise operations, without copying data. It is one of the most powerful ideas in NumPy.
import numpy as np
prices = np.array([[10.0, 20.0, 30.0],
[ 5.0, 15.0, 25.0]])
tax = np.array([1.1, 1.2, 1.0]) # one rate per column
print(prices * 2) # scalar broadcast to (2, 3)
print(prices * tax) # row (3,) broadcast down both rows[[20. 40. 60.]
[10. 30. 50.]]
[[11. 24. 30. ]
[ 5.5 18. 25. ]]
The rules
NumPy compares the two shapes from the right (the last dimension first). Two dimensions are compatible when:
- they are equal, or
- one of them is 1.
If one array has fewer dimensions, its shape is padded with 1s on the left. A dimension of size 1 is then stretched to match the other.
| Shape A | Shape B | Result | Why |
|---|---|---|---|
(2, 3) |
() (scalar) |
(2, 3) |
scalar fits everything |
(2, 3) |
(3,) |
(2, 3) |
(3,) → (1, 3) → stretched to 2 rows |
(4, 1) |
(3,) |
(4, 3) |
both stretched: an outer operation |
(2, 3) |
(2,) |
error | last dims 3 vs 2 |
(2, 3) |
(2, 1) |
(2, 3) |
column stretched across 3 columns |
You can check a combination without computing anything using np.broadcast_shapes:
import numpy as np
print(np.broadcast_shapes((2, 3), (3,)))
print(np.broadcast_shapes((4, 1), (3,)))
print(np.broadcast_shapes((5, 1, 7), (6, 1)))
try:
np.broadcast_shapes((2, 3), (2,))
except ValueError as err:
print("ValueError:", err)(2, 3)
(4, 3)
(5, 6, 7)
ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (2, 3) and arg 1 with shape (2,).
Row vectors, column vectors and outer operations
To operate on each row with its own value, you need a column of shape (n, 1). Turning a 1-D array into a column with [:, np.newaxis] (or .reshape(-1, 1)) is the key trick:
import numpy as np
scores = np.array([[70, 80, 90],
[60, 65, 70]])
row_means = scores.mean(axis=1) # shape (2,)
print(row_means)
centered = scores - row_means[:, np.newaxis] # (2, 3) - (2, 1)
print(centered)
# Without the new axis, shapes (2, 3) and (2,) don't match
try:
scores - row_means
except ValueError as err:
print("ValueError:", err)[80. 65.]
[[-10. 0. 10.]
[ -5. 0. 5.]]
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
Combining a column (n, 1) with a row (m,) produces a full (n, m) grid, an outer operation. That is how you build a multiplication table or a distance grid without loops:
import numpy as np
a = np.arange(1, 6)
table = a[:, np.newaxis] * a # (5, 1) * (5,) -> (5, 5)
print(table)
# Distances between 3 points on a line, all pairs at once
pts = np.array([0.0, 2.5, 7.0])
print(np.abs(pts[:, None] - pts))[[ 1 2 3 4 5]
[ 2 4 6 8 10]
[ 3 6 9 12 15]
[ 4 8 12 16 20]
[ 5 10 15 20 25]]
[[0. 2.5 7. ]
[2.5 0. 4.5]
[7. 4.5 0. ]]
A practical example: normalising data
Machine-learning code often rescales each column (feature) to mean 0 and standard deviation 1. axis=0 gives one statistic per column, shape (n_features,), which broadcasts over all rows automatically:
import numpy as np
# Rows = houses; columns = size (m2), rooms, age (years)
X = np.array([[120.0, 4, 15],
[ 80.0, 3, 40],
[200.0, 6, 5],
[ 95.0, 3, 22]])
mean = X.mean(axis=0)
std = X.std(axis=0)
Z = (X - mean) / std # (4, 3) - (3,) then / (3,)
print(Z.round(2))
print("column means now:", Z.mean(axis=0).round(10) + 0.0)[[-0.08 0. -0.43]
[-0.95 -0.82 1.53]
[ 1.65 1.63 -1.21]
[-0.62 -0.82 0.12]]
column means now: [0. 0. 0.]
To normalise each row instead, use keepdims=True, so the statistics keep shape (n, 1) and line up with the rows:
import numpy as np
counts = np.array([[2, 3, 5],
[10, 0, 10]])
shares = counts / counts.sum(axis=1, keepdims=True) # (2, 3) / (2, 1)
print(shares)[[0.2 0.3 0.5]
[0.5 0. 0.5]]
Tip: Broadcasting doesn't actually copy the smaller array; NumPy just reuses its values. But the result is full-size. Broadcasting
(10000, 1)against(10000,)creates a 100-million-element array (800 MB of floats), so keep an eye on result shapes.
Test yourself
What is the shape of np.ones((3, 1)) + np.ones(4)?
- (3, 1)
- (4,)
- (3, 4)
- An error
Which pair of shapes can NOT be broadcast together?
- (5, 3) and (3,)
- (5, 3) and (5, 1)
- (5, 3) and (5,)
- (5, 3) and ()
How do you subtract each row's mean from a 2-D array a?
- a - a.mean(axis=1)
- a - a.mean(axis=1, keepdims=True)
- a - a.mean()
- a - a.mean(axis=0)