Broadcasting in Python
Combining arrays of different shapes without loops.
import numpy as np
prices = np.array([10.0, 20.0, 30.0])
taxed = prices * 1.15
shifted = prices + 5
matrix = np.arange(6).reshape(2, 3)
col_bias = np.array([100, 200])
biased = matrix + col_bias[:, np.newaxis]
row = np.array([1, 2, 3])
outer = row[:, np.newaxis] * row[np.newaxis, :]
How it works
- A scalar spreads across the whole array.
newaxisreshapes so shapes line up.- An outer product falls out of two 1-D arrays.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 12
- Characters to type
- 286
- Tokens
- 100
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.
Step 1 of 4 in Math & shapes, step 3 of 22 in NumPy.