NumPy Differences
diff subtracts neighbouring values along an axis. It shortens that axis unless you deliberately supply a prepend or append value.
How it works
This is useful for changes in a cumulative meter reading, but only when resets, missing intervals and units are understood. Unsigned integer subtraction can wrap instead of representing a negative change, so cast to an appropriate signed type first. A first difference describes change, not a rate; divide by a validated time interval when a rate is actually required.
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 differences.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
meter = np.array([100, 112, 130, 154], dtype=np.int64)
change = np.diff(meter)
print(change.tolist())
print(change.shape)
print(np.diff(meter, n=2).tolist())
Expected result
[12, 18, 24] (3,) [6, 6]
The three first differences recover interval collections from four cumulative readings. The second differences describe how those interval changes themselves vary. A meter reset would need a separate rejection or correction policy.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.