Broadcasting is how NumPy does math between arrays of different shapes. The smaller array is stretched — virtually, without copying — to match the bigger one.
An array and a single number
Example
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 10)
Output
[10 20 30]
The single value 10 is broadcast to every element. You have been using broadcasting since the first lesson.
A 2-D array and a row
Example
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
row = np.array([10, 20, 30])
print(matrix + row)
Output
[[11 22 33]
[14 25 36]]
The row is added to each row of the matrix.
A 2-D array and a column
Example
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
column = np.array([[100], [200]])
print(matrix + column)
Output
[[101 102 103]
[204 205 206]]
The broadcasting rules
NumPy compares the two shapes starting from the last dimension. Two dimensions are compatible when:
they are equal, or
one of them is 1
So a (2, 3) array works with (3,) and with (2, 1), but not with (2,):
Example
import numpy as np
matrix = np.ones((2, 3))
try:
matrix + np.array([1, 2])
except ValueError as error:
print("Error:", error)
Output
Error: operands could not be broadcast together with shapes (2,3) (2,)
A practical example: centering data
Subtracting each column's mean from that column is one line with broadcasting:
Example
import numpy as np
data = np.array([[1.0, 200.0],
[3.0, 400.0],
[5.0, 600.0]])
centered = data - data.mean(axis=0)
print(centered)
Output
[[ -2. -200.]
[ 0. 0.]
[ 2. 200.]]