cumsum() and cumprod() (NumPy)
np.cumsum() returns the running (cumulative) sum of an array — each element is the total of all elements up to that point — and np.cumprod() returns the running product. They keep the same length as the input.
NumPy
Unlike sum, which collapses to a single value, cumsum produces an array of running totals: [1, 2, 3, 4] becomes [1, 3, 6, 10]. This is exactly what you need for things like a running balance, a cumulative distribution, or progress toward a total.
cumprod does the same for multiplication, useful for compounding growth factors or computing cumulative probabilities. Both accept an axis argument so you can accumulate down columns or across rows of a 2-D array, just like the reduction functions.
Because the result keeps the original length, these 'scan' operations differ from reductions, which shrink a dimension away. The nan-aware nancumsum and nancumprod skip missing values.
Syntax
np.cumsum(a, axis=None) | np.cumprod(a, axis=None)Examples
Python
import numpy as np
print(np.cumsum(np.array([1, 2, 3, 4])))Output:
[ 1 3 6 10]