NumPy Weighted Averages
A weighted average gives values different contributions according to an explicit rule. The weights might be observation counts, exposure time or another justified quantity.
How it works
The sum of the weights must support a valid denominator. Negative weights have specialized mathematical uses but are unsuitable for many ordinary measurement summaries. When combining chunk averages, their counts are the appropriate weights if the goal is the overall observation mean. Using an unweighted mean of unequal chunk means answers a different question and can give a misleading result.
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 weighted-averages.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
chunk_means = np.array([10., 20.])
counts = np.array([2, 6])
print(float(np.average(chunk_means, weights=counts)))
print(float(chunk_means.mean()))
print(int(counts.sum()))
Expected result
17.5 15.0 8
The larger chunk contributes six of eight observations, so the combined mean is seventeen and a half. The unweighted result treats the two chunks as equally important groups instead of weighting each observation equally.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.