NumPy Broadcasting
Broadcasting aligns shapes from their trailing dimensions. Corresponding lengths must match or one of them must be one.
How it works
A calibration value per site needs shape (sites, 1) to align across every day. A value per day can have shape (days,). Write the expected result shape before performing the operation. Broadcasting can avoid copying the smaller input, but the calculated output may still be large. An accidental outer expansion can allocate far more memory than intended, even when the operation is valid.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python broadcasting.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
litres = np.array([[12, 18, 24], [6, 9, 15]])
adjustment = np.array([1, 2])[:, None]
print(adjustment.shape)
print((litres + adjustment).tolist())
try:
litres + np.array([1, 2])
except ValueError:
print("Rejected incompatible trailing axis")
Expected result
(2, 1) [[13, 19, 25], [8, 11, 17]] Rejected incompatible trailing axis
Each site gets its own adjustment across three days. The unshaped two-value vector cannot align with the three-day trailing axis and is rejected. This is an axis-design issue rather than a need to duplicate values manually.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.