Cumulative Statistics in Pandas – cumsum, cummax, cummin, expanding() & More in Python 2026
Cumulative statistics allow you to calculate running totals, running maximums, running averages, and other metrics that update as you move through your data. These are extremely valuable for trend analysis, growth tracking, and creating powerful features in data manipulation workflows.
TL;DR — Key Cumulative Functions
.cumsum()– Running total.cummax()– Running maximum.cummin()– Running minimum.cumprod()– Running product.expanding().mean()– Running (expanding window) average.expanding().std()– Running standard deviation
1. Basic Cumulative Statistics
import pandas as pd
# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
"order_date": pd.date_range("2025-10-01", periods=n, freq="3D"),
"customer_id": rng.integers(101, 121, n),
"customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
"product_id": rng.integers(1, 9, n),
"region": rng.choice(["North", "South", "East", "West"], n),
"category": rng.choice(["Electronics", "Books", "Home"], n),
"payment_method": rng.choice(["card", "cash", "wallet"], n),
"segment": rng.choice(["consumer", "business"], n),
"quantity": rng.integers(1, 6, n),
"amount": rng.uniform(50, 2500, n).round(2),
}).assign(
ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
df = df.sort_values("order_date")
# Running totals
df["cum_sales"] = df["amount"].cumsum()
df["cum_quantity"] = df["quantity"].cumsum()
# Running maximum and minimum
df["running_max_sale"] = df["amount"].cummax()
df["running_min_sale"] = df["amount"].cummin()
2. Running Averages and Statistics with expanding()
# Running (expanding window) statistics
df["running_avg_sale"] = df["amount"].expanding().mean()
df["running_std_sale"] = df["amount"].expanding().std()
df["running_min"] = df["amount"].expanding().min()
3. Grouped Cumulative Statistics (Most Powerful Pattern)
# Cumulative sales per region
df["cum_sales_by_region"] = df.groupby("region")["amount"].cumsum()
# Running average per customer
df["customer_running_avg"] = df.groupby("customer_id")["amount"].expanding().mean().reset_index(level=0, drop=True)
4. Real-World Example: Monthly Cumulative Growth
monthly = (
df
.groupby([df["order_date"].dt.to_period("M"), "region"])
.agg(total_sales=("amount", "sum"))
.reset_index()
)
monthly["cumulative_sales"] = monthly.groupby("region")["total_sales"].cumsum()
monthly["cumulative_growth"] = monthly.groupby("region")["cumulative_sales"].pct_change()
Best Practices in 2026
- Always sort your data by the time column before applying cumulative functions
- Use
groupby()+ cumulative methods for segmented running statistics - Combine
cumsum()withexpanding()for rich feature engineering - Use
.fillna(0)if your data contains NaNs before cumulative calculations - These operations are very fast in Pandas and scale well to large datasets
Cumulative vs Expanding vs Rolling
The cum* methods cover sums, products, minimum and maximum. For anything else, such as a running mean, median or standard deviation, use expanding(), which grows its window from the first row to the current one. rolling(n) is different: it keeps a fixed-size window of the last n rows, so old values drop out. Both work on a Series, a DataFrame or a grouped object, and both accept a time-based window on a datetime index, such as rolling("7D"). Running statistics answer "how are we doing overall so far?", while rolling statistics answer "how are we doing lately?".
Worked Example: Overall vs Recent Average
This example compares an expanding mean with a three-day rolling mean on the same values.
import pandas as pd
s = pd.Series([10, 12, 11, 30, 32, 31],
index=pd.date_range("2026-03-01", periods=6, freq="D"))
out = pd.DataFrame({
"value": s,
"running_mean": s.expanding().mean().round(2),
"last_3_mean": s.rolling(3).mean().round(2),
})
print(out)
After the jump on day four, the rolling mean reaches 31.0 within three days, while the running mean moves more slowly (21.0 on the last day) because it still includes the early values. Use min_periods to control how many rows are needed before a value is shown.
Common Mistakes
- Using
cumsum() / countby hand:expanding().mean()handles missing values correctly - Expecting values in the first rolling rows:
rolling(3)returns NaN until three rows exist - Mixing groups: call
groupby(key)["col"].expanding().mean()so each group starts fresh - Unsorted time index: sort with
sort_index()first
Quick Summary
expanding()gives any running statisticrolling(n)looks only at recent rows- Sort and group before calculating
Conclusion
Cumulative statistics are a powerful addition to any data manipulation toolkit. In 2026, combining cumsum(), cummax(), expanding(), and groupby() allows you to create insightful running metrics, growth trends, and historical comparisons with minimal code. These techniques turn static transactional data into dynamic, time-aware insights.
Next steps:
- Add cumulative sales and running average columns to one of your current datasets and explore the new insights they reveal