Sub topic 12
Running totals with cumsum
This chapter covers cumulative functions along an axis. It assumes you can create arrays with np.array and np.arange, read an array's shape, and use axis with sum, max, and mean. It also assumes you know that a reduction removes the axis it runs over.
Reductions versus cumulative functions
A reduction such as sum collapses an axis. A cumulative function walks along an axis and records the running result at every position. The input shape is kept.
| Function | What it does along the axis | Result shape |
|---|---|---|
| `sum` | One total per line | Axis removed |
| `cumsum` | Running total at each position | Same as input |
| `prod` | One product per line | Axis removed |
| `cumprod` | Running product at each position | Same as input |
The axis argument works as it does for reductions. axis=0 runs down the rows, so each column gets its own running total. axis=1 runs across the columns, so each row gets its own running total.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.cumsum(a))
# [ 1 3 6 10 15 21]
print(np.cumsum(a, axis=0))
# [[1 2 3]
# [5 7 9]]
print(np.cumsum(a, axis=1))
# [[ 1 3 6]
# [ 4 9 15]]
print(np.cumsum(a, axis=1).shape) # (2, 3)With axis=0, the second row is [1+4, 2+5, 3+6]. With axis=1, each row is accumulated on its own. The shape stays (2, 3) in every case where an axis is given.
The no-axis case flattens the array
The first call above has no axis. For cumsum, that is different from sum. sum() with no axis returns a scalar, and cumsum() with no axis flattens the array in row-major order and returns a one-dimensional result of length a.size.
The output is therefore not a 2D array, even though the input was. If you want to keep the shape, always pass axis.
A worked example: cumulative sales
Suppose each row is a day and each column is a store. A running total down the rows gives each store's sales to date.
import numpy as np
sales = np.array([[10, 20, 5],
[15, 0, 5],
[ 5, 10, 10],
[20, 5, 0]])
to_date = np.cumsum(sales, axis=0)
print(to_date)
# [[10 20 5]
# [25 20 10]
# [30 30 20]
# [50 35 20]]
print(to_date[-1]) # [50 35 20]
print(sales.sum(axis=0)) # [50 35 20]The last row of the running totals equals the column reduction. This gives a quick consistency check: cumsum along an axis ends with the same values that sum along that axis returns. For integers the match is exact. For floats the two can differ in the last digits, because sum may add the values in a different order. Compare floats with np.allclose, not ==.
Going back: np.diff
np.diff computes differences between neighbors along an axis, so it undoes cumsum. A plain diff returns one element fewer along that axis. Pass prepend=0 to get back the first element as well.
import numpy as np
sales = np.array([[10, 20, 5],
[15, 0, 5],
[ 5, 10, 10],
[20, 5, 0]])
to_date = np.cumsum(sales, axis=0)
restored = np.diff(to_date, axis=0, prepend=0)
print(np.diff(to_date, axis=0).shape) # (3, 3)
print(restored.shape) # (4, 3)
print(np.array_equal(restored, sales)) # TrueThe scalar prepend=0 is expanded to a single row of zeros along the chosen axis, so the first output row is to_date[0] - 0.
Running share with keepdims
Cumulative functions combine well with the keepdims technique from earlier chapters. To find what fraction of each row's total has been reached at each column, divide the running total by the row total.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
running = np.cumsum(a, axis=1) # shape (2, 3)
totals = a.sum(axis=1, keepdims=True) # shape (2, 1)
share = running / totals
print(np.round(share, 2))
# [[0.17 0.5 1. ]
# [0.27 0.6 1. ]]The shapes (2, 3) and (2, 1) broadcast, so each row is divided by its own total. The last column is always 1.0 because the last running total equals the row total. Without keepdims=True, the totals would have shape (2,). NumPy would then try to align that with the last axis of length 3 and raise a ValueError.
Other cumulative operations
cumprod multiplies instead of adding.
import numpy as np
print(np.cumprod([1, 2, 3, 4])) # [ 1 2 6 24]Products grow fast, so overflow is a real risk for integer inputs (see the next section).
For a running maximum or minimum there is no cummax function. Use the accumulate method of the underlying ufunc (universal function, NumPy's element-wise operation type) instead. It takes an axis argument like cumsum does.
import numpy as np
b = np.array([[3, 1, 4, 1],
[2, 7, 1, 8]])
print(np.maximum.accumulate(b, axis=1))
# [[3 3 4 4]
# [2 7 7 8]]np.add.accumulate is the same operation as np.cumsum. Any binary ufunc can accumulate, and np.minimum.accumulate gives running minimums.
Data types and overflow
The type of a cumulative result matters more than the type of a reduction, because every element of the output is a partial total that can overflow. For integer inputs narrower than the platform integer, cumsum and cumprod accumulate in the platform integer (usually 64-bit) by default. You can override this with dtype.
import numpy as np
x = np.array([100, 100, 100], dtype=np.int8)
print(np.cumsum(x)) # [100 200 300]
print(np.cumsum(x).dtype) # int64 on most platforms
print(np.cumsum(x, dtype=np.int8)) # [ 100 -56 44]With dtype=np.int8, the values wrap around modulo 256. NumPy gives no warning for integer array overflow. Do not request a narrow dtype unless you are sure the totals fit.
Boolean arrays are summed as 0 and 1, which makes cumsum a counting tool.
import numpy as np
hits = np.array([True, False, True, True])
print(np.cumsum(hits)) # [1 1 2 3]Missing values
A NaN poisons every running total after it, because NaN plus anything is NaN. This differs from sum, where one NaN spoils one result. In a cumulative result, all later positions along that axis are lost.
np.nancumsum treats NaN as 0 and keeps going. np.nancumprod treats NaN as 1.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(np.cumsum(c, axis=0))
# [[ 1. nan]
# [ 4. nan]]
print(np.nancumsum(c, axis=0))
# [[1. 0.]
# [4. 4.]]Unlike nansum, which skips NaN and returns a smaller total, nancumsum must keep the output shape. The position that held NaN therefore shows the running total so far (here 0, since nothing came before it in that column). Treat that value as "unknown, carried forward", not as a measurement.
Common mistakes
- Forgetting
axis. The result is a flat array, and the values run across row boundaries. - Using the wrong direction. If each column is a store and you want per-store history, you need
axis=0. A quick test is to check that the last row (or column) of the result equals the matchingsum. - Expecting the axis to disappear. Cumulative functions keep the shape, so there is no need for
keepdims. You only needkeepdimson the reduction you divide by. - Narrow integer types. Check the
dtypeof products in particular, and pass a widerdtypewhen the data is small integers. - NaN propagation. Decide whether NaN should carry forward as NaN or be treated as 0 before choosing between
cumsumandnancumsum.
Exercise
A 2D array temps has shape (7, 3). Each row is a day of the week, and each column is a city. It holds the rainfall in mm. Write an expression that gives each city's total rainfall up to and including each day, and say what shape it has and which values the last row holds.
Show answer
np.cumsum(temps, axis=0). The shape is (7, 3), the same as the input, because cumulative functions keep the shape. The last row holds each city's weekly total, which equals temps.sum(axis=0).
Exercise
Given a = np.array([[2, 2, 4], [1, 3, 6]]), compute the running share of each row, as in the share example above. What does the output look like when printed with np.round(..., 2)? Why does a.sum(axis=1) without keepdims=True fail in the division?
Show answer
Use np.cumsum(a, axis=1) / a.sum(axis=1, keepdims=True). The row totals are 8 and 10, so the output is [[0.25 0.5 1. ] and [0.1 0.4 1. ]]. Without keepdims, the totals have shape (2,), which NumPy tries to align with the last axis of length 3. The shapes (2, 3) and (2,) are incompatible, so a ValueError is raised.
Exercise
What does np.cumsum(np.array([100, 100, 100], dtype=np.int8), dtype=np.int8) return, and why?
Show answer
It returns [100 -56 44]. An int8 holds values from -128 to 127, so 200 wraps to -56 and 300 wraps to 44. NumPy does not warn about integer overflow in array operations.