Broadcasting basics
Broadcasting lets NumPy stretch a smaller array so it can be combined with a bigger one without copying data.
In this page:
Syntax
# shapes are compared from the last axis backwards
result = arr_shape_3_by_1 + arr_shape_1_by_4 # -> shape (3, 4)
Broadcasting basics
When shapes differ, NumPy compares them from the last axis backwards. Dimensions are compatible if they are equal or one of them is 1, and the size-1 axis is stretched. This lets you add a row to every row of a matrix in one expression.
Note:
If broadcasting fails you will see a ValueError mentioning operands could not be broadcast together.
Example: Broadcasting basics
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
row = np.array([10, 20, 30])
col = np.array([[100], [200]])
print(m + row)
print(m + col)
# Output:
# [[11 22 33]
# [14 25 36]]
# [[101 102 103]
# [204 205 206]]
Related Topics
Common Mistakes
- Assuming any two shapes can be combined
- Mixing up which axis is stretched
- Forgetting a 1-D array aligns with the last axis
Chapter Summary
- Compare shapes from the right
- Axes must be equal or 1
- Size-1 axes stretch
- Avoids explicit loops and copies
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: