Cumulative Statistics in Pandas – cumsum, cummax, cummin, expanding() & More in Python 2026

Data Manipulation Mar 18, 2026

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() with expanding() 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() / count by 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 statistic
  • rolling(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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices