cumsum
df["col"].cumsum() returns the running total: each row holds the sum of all values up to and including that row. df.groupby("key")["col"].cumsum() restarts the total for each group while keeping one value per original row.
Syntax
Series.cumsum(skipna=True) | Series.cumprod() | Series.cummax() | Series.cummin()Examples
import pandas as pd
df = pd.DataFrame({"month": ["Jan", "Feb", "Mar"], "sales": [100, 120, 90]})
df["ytd"] = df["sales"].cumsum()
dfResult: month sales ytd 0 Jan 100 100 1 Feb 120 220 2 Mar 90 310
g = pd.DataFrame({"id": ["a", "a", "b", "b"], "v": [1, 2, 10, 20]})
g["run"] = g.groupby("id")["v"].cumsum()
gResult: id v run 0 a 1 1 1 a 2 3 2 b 10 10 3 b 20 30
(df["sales"].cumsum() / df["sales"].sum() * 100).round(1).tolist()Result: [32.3, 71.0, 100.0]
Cumulative percentage of the total.
Common mistakes
- The running total is in the wrong order: cumsum follows row order, so sort by date first.
- NaN breaks the sequence: with skipna=True NaN rows stay NaN and the total continues after; fill them with 0 if they mean zero.
- Using sum when you want cumsum: sum returns a single number, cumsum one number per row.
Practice cumsum
These drills check your answer on live data, free, no account needed.
- Running totalReturn the running total of `signups`, day by day.
Questions
How do I reset the cumulative sum when a condition is met?
Create a group id that increments at each reset, for example grp = cond.cumsum(), then df.groupby(grp)["v"].cumsum().
How do I count rows cumulatively per group?
df.groupby("id").cumcount() + 1 numbers the rows 1, 2, 3 within each group.
Related
- rollingHow to compute a moving average in pandas with rolling: window size, min_periods to avoid leading NaN, centered windows, rolling sum and std, time windows.
- shift and diffHow to use shift and diff in pandas to get the previous or next row, compute the change and percent change between periods, and lag within groups.
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
- transformHow groupby transform works in pandas: broadcast a group sum or mean to each row, share of group total, group-wise normalization, and transform versus agg.