Running totals
Create running totals from a one-dimensional sequence such as transaction amounts.
NumPy · Function
Computes cumulative sums along an axis of an array. By default, multidimensional input is flattened before accumulation.
NumPy converts the input to an array and accumulates sums along the selected axis. With no axis, it processes the flattened input; dtype controls the accumulator and result type, while out can receive the result in a supplied array.
numpy.cumsum(a, axis=None, dtype=None, out=None)| Name | Type | Description |
|---|---|---|
a | array_like | Input array. |
axis | int, optional | Axis along which the cumulative sum is computed. The default, None, computes over the flattened array. |
dtype | dtype, optional | Type of the returned array and the accumulator used for summation. |
out | ndarray, optional | Array in which to place the result; it must have the expected shape and buffer length, with casting applied if needed. |
An ndarray containing cumulative sums, with the same size as the input; its shape matches the input when axis is specified or the input is one-dimensional. If out is supplied, a reference to out is returned.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(np.cumsum(a, axis=1))
# [[ 1 3 6]
# [ 4 9 15]]Computes running totals independently across each row.
Create running totals from a one-dimensional sequence such as transaction amounts.
Generate row-wise or column-wise cumulative measurements in a matrix.
Write results into preallocated NumPy storage to reduce additional allocation.
It computes cumulative sums along an axis, where each output element includes the current input element and all preceding elements along that axis. If axis is None, the input is flattened first.
Follow-up: How would you preserve row structure for a 2-D array? Pass axis=1 for running totals within rows, or axis=0 for running totals down columns.
dtype selects the type of both the returned array and the accumulator used during summation. Choosing a suitable dtype can control precision or reduce integer-overflow risk.
Follow-up: What caveat remains for floating-point inputs? Cumulative addition can differ from a separately grouped sum because floating-point arithmetic is not exact.
out is an optional ndarray that receives the result instead of requiring a newly allocated output. It must match the expected shape and buffer length, and values are cast to its type when necessary.
Follow-up: What should be checked when using out? Ensure its shape is compatible and its dtype can represent the intended result without unwanted casting.
numpy.ndarray.cumsumnumpy.sum