Sub topic 9
Broadcasting rules
Broadcasting lets NumPy combine arrays of different shapes without copying data. This chapter assumes you can create arrays, read shape, and use elementwise arithmetic on arrays of equal shape.
The two rules
NumPy compares two shapes starting from the last (rightmost) dimension and moves left.
- If the shapes have different lengths, pad the shorter one with 1s on the left.
- For each dimension, the sizes must be equal, or one of them must be 1. A dimension of size 1 is stretched to match the other.
If any dimension fails both tests, NumPy raises a ValueError.
A worked example
A column vector and a 1-D array combine into a 2-D result.
import numpy as np
x = np.array([[1], [2], [3]]) # shape (3, 1)
y = np.array([10, 20, 30]) # shape (3,)
z = x + y # broadcast to shape (3, 3)
print(z)
# [[11 21 31]
# [12 22 32]
# [13 23 33]]Apply the rules step by step:
yhas shape(3,). Padding on the left gives(1, 3).- Compare
(3, 1)with(1, 3). In the last dimension, 1 stretches to 3. In the first dimension, 1 stretches to 3. - The result shape is
(3, 3).
The stretching is virtual. NumPy does not build a 3x3 copy of x or y. It reuses the same memory by giving the stretched dimension a stride of 0.
Common uses
Broadcasting is how you apply a scalar or a per-row or per-column value to a whole array. A scalar behaves like a shape () array, which is padded to match any shape.
import numpy as np
m = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]]) # shape (2, 3)
print(m * 10) # scalar applies to every element
print(m - m.mean(axis=0)) # (2, 3) - (3,): center each column
print(m / m.sum(axis=1, keepdims=True)) # (2, 3) / (2, 1): normalize each rowThe last line shows why keepdims=True matters. Without it, m.sum(axis=1) has shape (2,). That is padded to (1, 2), which does not match (2, 3).
Common errors
A mismatch raises an error that lists both shapes.
import numpy as np
a = np.ones((2, 3))
b = np.ones((2,))
try:
a + b
except ValueError as e:
print(e)
# operands could not be broadcast together with shapes (2,3) (2,)Here (2,) becomes (1, 2). The last dimensions are 3 and 2, which are unequal and neither is 1. To subtract a per-row value, add an axis so the shape is (2, 1).
import numpy as np
a = np.ones((2, 3))
b = np.array([10.0, 20.0])
print(a + b[:, np.newaxis]) # b becomes shape (2, 1)
# [[11. 11. 11.]
# [21. 21. 21.]]Exercise
What is the result shape of adding arrays with shapes (4, 1, 3) and (5, 1)? Does the operation succeed?
Show answer
It succeeds with shape (4, 5, 3). The second shape is padded to (1, 5, 1). Comparing from the right: 3 and 1 give 3, 1 and 5 give 5, and 4 and 1 give 4.