bhylu.com

Advertisements

NumPy Reductions

sum, mean, min and max combine values along selected axes. keepdims retains reduced axes with length one so later broadcasting remains clear.

How it works

A site-by-day table can produce one average per site. Keeping the day axis allows that average to be subtracted from each day in the same row. Without keepdims, the shorter result may align with an unintended axis or fail to broadcast. Reduction dtypes and accumulation precision also matter for large or narrow input types, so choose an accumulation type when a range analysis requires it.

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 reductions.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

reductions.py

import numpy as np

litres = np.array([[12., 18., 24.], [6., 9., 15.]])
means = litres.mean(axis=1, keepdims=True)
print(means.tolist())
print((litres - means).tolist())
print(means.shape)

Expected result

[[18.0], [10.0]]
[[-6.0, 0.0, 6.0], [-4.0, -1.0, 5.0]]
(2, 1)

The averages stay in a two-row, one-column shape and subtract from the correct sites. The centered rows sum to zero apart from possible floating-point rounding in less exact datasets.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.