Sub topic 12
Running totals with cumsum
This chapter assumes you know how axis works in sum, mean, and max, and that you can read an array's shape. A reduction such as sum removes the axis it runs along. A cumulative function keeps every position, so the output has the same shape as the input.
What cumsum computes
np.cumsum returns the running total of the values it passes over. Each output element is the sum of all input elements up to and including that position.
import numpy as np
v = np.array([1, 2, 3, 4])
print(np.cumsum(v)) # [ 1 3 6 10]
print(v.sum()) # 10The last element of the running total always equals the plain sum.
Choosing the direction with axis
On a two-dimensional array, axis picks the direction the total accumulates in.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
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)axis=0accumulates down each column. The second row becomes1+4,2+5,3+6.axis=1accumulates across each row. The first row becomes1,1+2,1+2+3.
The meaning of axis is the same as for sum. Only the result differs: sum removes the axis, and cumsum keeps it.
The default flattens the array
If you leave out axis, cumsum first flattens the array in row-major order and returns a one-dimensional result.
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).shape) # (6,)This differs from sum(), where leaving out axis also covers the whole array but gives a single number. If you expect a two-dimensional result, always pass axis.
Checking the result against sum
The last slice along the accumulated axis should match the reduction. This is a quick sanity check.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
running = a.cumsum(axis=1)
print(running[:, -1]) # [ 6 15]
print(a.sum(axis=1)) # [ 6 15]Related cumulative functions
Other cumulative functions follow the same rules for axis and shape.
np.cumprodgives running products.np.nancumsumtreatsNaNas 0, so one missing value does not turn the rest of the running total intoNaN.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.cumprod(a, axis=1))
# [[ 1 2 6]
# [ 4 20 120]]
c = np.array([1.0, np.nan, 3.0])
print(np.cumsum(c)) # [ 1. nan nan]
print(np.nancumsum(c)) # [1. 1. 4.]Data types
Integer running totals grow quickly. For small integer types and booleans, cumsum accumulates in the platform integer by default, which avoids most overflow. You can set the accumulator type yourself with the dtype argument, for example a.cumsum(axis=1, dtype=np.float64).
Exercise
Exercise
The array sales = np.array([[10, 20, 30], [5, 5, 5]]) has one row per product and one column per month. Which call gives each product's cumulative sales over the months, and what does it return?
Show answer
sales.cumsum(axis=1). Months run along the columns, so the total accumulates along axis 1. The result is [[10 30 60] [ 5 10 15]] with shape (2, 3).