Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Python

Calculating Cumulative and Rolling Metrics by Group in pandas: Running Totals, Moving Averages, and Period-to-Date Summaries with groupby and transform

Learn how to calculate running totals, moving averages, and MTD/YTD summaries that reset correctly for each group using pandas groupby and transform. No fragile Excel formulas — just clean, reliable Python code that works on real datasets.

🌱 Foundation14 min readNov 24, 2026Updated Nov 24, 2026
Calculating Cumulative and Rolling Metrics by Group in pandas: Running Totals, Moving Averages, and Period-to-Date Summaries with groupby and transform
On this page
  • Introduction
  • Prerequisites
  • The Setup: A Realistic Dataset
  • Understanding transform: Why It's Different from agg
  • Running Totals by Group with cumsum
  • Moving Averages by Group with rolling
  • Period-to-Date Summaries: MTD and YTD
  • Combining Metrics into a Report-Ready DataFrame
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Calculating Cumulative and Rolling Metrics by Group in pandas: Running Totals, Moving Averages, and Period-to-Date Summaries with groupby and transform

Introduction

Imagine you're a sales analyst and your manager asks for a report that shows each salesperson's running total of revenue for the quarter — not just their grand total, but how their cumulative sales built up week by week. Or maybe you need to flag which transactions are above a rep's own 4-week moving average, so you can spot unusual spikes. In Excel, you'd probably write a formula that references earlier rows, carefully adjusting for each person's section of the spreadsheet. It works, but it breaks the moment someone adds a row or changes the sort order.

pandas gives you a better way. Using groupby combined with transform, cumsum, and rolling, you can calculate these kinds of within-group running metrics in a few lines of code — and the result lands right back in your original DataFrame as a new column, perfectly aligned with every row. No manual formula dragging, no fragile cell references.

By the end of this lesson, you'll be able to calculate running totals, moving averages, and period-to-date summaries that reset correctly for each group. That last part — "that reset correctly for each group" — is what makes this genuinely hard to do in Excel and genuinely easy once you understand how pandas handles it.

What you'll learn:

  • Why transform is the right tool when you want group-level results to appear as new columns in your original DataFrame
  • How to calculate cumulative sums and cumulative averages within groups using groupby + transform + cumsum
  • How to build rolling (moving) averages that restart for each group
  • How to calculate period-to-date (MTD, QTD, YTD) summaries that reset at the right boundaries
  • How to combine these techniques to build a genuinely useful analytical report

Prerequisites

You should be comfortable creating and filtering DataFrames before working through this lesson. If you're new to pandas, start with Your First pandas DataFrame: Loading CSV and Excel Files and Exploring Data first. You should also understand what groupby does at a basic level — the article on Grouping and Aggregating in pandas: groupby as the PivotTable Replacement covers that foundation.

Working with dates is central to period-to-date calculations. If date parsing and manipulation feel unfamiliar, Working with Dates and Time Series in pandas: Parsing, Resampling, and Rolling Windows is a great companion read.


The Setup: A Realistic Dataset

Let's build a dataset that mirrors something you'd actually encounter: weekly sales transactions for a small team of sales reps across two regions, covering six months of 2024.

import pandas as pd
import numpy as np

# Reproducible random data
rng = np.random.default_rng(42)

reps = ["Alice", "Bob", "Carol", "David"]
regions = {"Alice": "East", "Bob": "East", "Carol": "West", "David": "West"}

dates = pd.date_range(start="2024-01-01", end="2024-06-30", freq="W-MON")

rows = []
for rep in reps:
    for date in dates:
        revenue = rng.integers(5_000, 30_000)
        rows.append({
            "week": date,
            "rep": rep,
            "region": regions[rep],
            "revenue": int(revenue),
        })

df = pd.DataFrame(rows)
df = df.sort_values(["rep", "week"]).reset_index(drop=True)

print(df.head(12))
         week    rep region  revenue
0  2024-01-01  Alice   East    22847
1  2024-01-08  Alice   East    11203
2  2024-01-15  Alice   East    27651
3  2024-01-22  Alice   East     8934
4  2024-01-29  Alice   East    19422
5  2024-02-05  Alice   East    24108
6  2024-02-12  Alice   East    15673
7  2024-02-19  Alice   East    29011
8  2024-02-26  Alice   East    12567
9  2024-03-04  Alice   East    21034
10 2024-03-11  Alice   East    17890
11 2024-03-18  Alice   East     9456

Each row is one week for one rep. This is exactly the structure where cumulative and rolling metrics get interesting — and where Excel formulas start to get unwieldy.


Understanding transform: Why It's Different from agg

Before writing a single cumulative calculation, you need to understand a conceptual distinction that trips up almost everyone who comes from Excel or SQL.

When you call groupby("rep").agg("sum"), pandas collapses your DataFrame. You get back one row per rep. That's great for a summary table, but useless if you want to add a new column to your original row-level data.

transform is different. It applies a function group by group, but it returns a Series the same length as the original DataFrame, with each value positioned at the right row. This is exactly what you need when you want to say "for each row, what is this rep's cumulative total up to this point?"

Key insight

agg reduces your DataFrame to fewer rows. transform keeps every row and returns group-computed values aligned to those same rows. Think of it like the difference between a SQL GROUP BY query (which aggregates) and a SQL window function like SUM() OVER (PARTITION BY rep ORDER BY week) (which doesn't collapse rows).

Here's the simplest possible demonstration of the difference:

# agg collapses - you get one row per rep
df.groupby("rep")["revenue"].agg("sum")

# transform keeps every row - result has same length as df
df.groupby("rep")["revenue"].transform("sum")

The second version gives you a column you can directly assign to df["rep_total_revenue"]. Every row for Alice gets Alice's total. Every row for Bob gets Bob's total. No merging required.


Running Totals by Group with cumsum

Now let's build the first real metric: a cumulative running total of revenue per rep, ordered by week.

The key is making sure the data is sorted by date before you calculate the cumulative sum. If the rows are in the wrong order, your running total will be meaningless.

# Ensure data is sorted correctly
df = df.sort_values(["rep", "week"]).reset_index(drop=True)

# Running total per rep
df["rep_running_total"] = df.groupby("rep")["revenue"].transform("cumsum")

print(df[["week", "rep", "revenue", "rep_running_total"]].head(14))
         week    rep  revenue  rep_running_total
0  2024-01-01  Alice    22847              22847
1  2024-01-08  Alice    11203              34050
2  2024-01-15  Alice    27651              61701
3  2024-01-22  Alice     8934              70635
4  2024-01-29  Alice    19422              90057
...
26 2024-01-01    Bob    18923              18923
27 2024-01-08    Bob    27104              46027

Notice that Bob's running total resets to his first week's revenue at row 26. That reset is automatic — groupby splits the data by rep before applying cumsum, so each rep gets their own independent running total. In Excel, you'd need a formula that detected when the rep name changed and conditionally restarted the sum.

Warning

Always sort your data by the time column before running cumulative calculations. If your DataFrame isn't sorted chronologically within each group, cumsum will produce numbers that look plausible but are wrong. Add df.sort_values(["rep", "week"], inplace=True) as a safety habit before any cumulative operation.

You can also calculate a cumulative average the same way using "cummean" — but note that pandas uses "expanding" syntax for this rather than a simple string shortcut. Here's the right approach:

# Cumulative mean requires the expanding approach
df["rep_cumulative_avg"] = (
    df.groupby("rep")["revenue"]
    .transform(lambda x: x.expanding().mean())
)

The expanding() method creates a window that grows with each new row — starting with just the first value, then the first two, then the first three, and so on. Combined with .mean(), it gives you the average of all values seen so far within the group.


Moving Averages by Group with rolling

A moving average (also called a rolling average) smooths out week-to-week noise by averaging each value with the N values before it. It's one of the most useful tools for spotting trends without being distracted by individual spikes.

The key concept: rolling(n) creates a window of the last n rows. For each row, it looks back at the current row plus the previous n-1 rows and computes whatever function you ask for.

# 4-week rolling average per rep
df["rep_rolling_4w_avg"] = (
    df.groupby("rep")["revenue"]
    .transform(lambda x: x.rolling(window=4).mean())
)

print(df[["week", "rep", "revenue", "rep_rolling_4w_avg"]].head(8))
         week    rep  revenue  rep_rolling_4w_avg
0  2024-01-01  Alice    22847                 NaN
1  2024-01-08  Alice    11203                 NaN
2  2024-01-15  Alice    27651                 NaN
3  2024-01-22  Alice     8934           17658.75
4  2024-01-29  Alice    19422           16802.50
5  2024-02-05  Alice    24108           20028.75
6  2024-02-12  Alice    15673           17034.25
7  2024-02-19  Alice    29011           22053.50

The first three rows for Alice show NaN because there aren't yet 4 weeks of data to average. This is correct behavior — a 4-week average needs 4 data points.

Tip

If you'd prefer a result even when fewer than window rows are available, add min_periods=1 to the rolling() call: x.rolling(window=4, min_periods=1).mean(). This tells pandas to compute the average with whatever data exists, even if that's just one row. Whether you want this depends on your use case — for trend detection, NaN in early rows is usually the right choice.

Now let's use the rolling average to flag weeks where a rep's revenue was significantly above their own recent trend — a classic anomaly detection pattern:

df["above_rolling_avg"] = df["revenue"] > df["rep_rolling_4w_avg"]

print(
    df[df["above_rolling_avg"]][["week", "rep", "revenue", "rep_rolling_4w_avg"]]
    .head(8)
)

This kind of rep-relative flagging is impossible to do cleanly with simple aggregation. You need the row-level result that transform provides.


Period-to-Date Summaries: MTD and YTD

Month-to-date (MTD) and year-to-date (YTD) summaries reset at the beginning of each month or year. The pattern is: group by rep and the period you want to reset on, then apply cumsum within that combined grouping.

First, extract the month and year from the date column:

df["year"] = df["week"].dt.year
df["month"] = df["week"].dt.month

Now, an MTD running total for each rep resets at the start of each month:

# MTD running total: resets at the start of each month, per rep
df["rep_mtd_revenue"] = (
    df.groupby(["rep", "year", "month"])["revenue"]
    .transform("cumsum")
)

# Check Alice's January and February
print(
    df[df["rep"] == "Alice"][["week", "month", "revenue", "rep_mtd_revenue"]]
    .head(10)
)
         week  month  revenue  rep_mtd_revenue
0  2024-01-01      1    22847            22847
1  2024-01-08      1    11203            34050
2  2024-01-15      1    27651            61701
3  2024-01-22      1     8934            70635
4  2024-01-29      1    19422            90057
5  2024-02-05      2    24108            24108   ← resets for February
6  2024-02-12      2    15673            39781
7  2024-02-19      2    29011            68792
8  2024-02-26      2    12567            81359

The cumulative total resets to Alice's first February value at row 5. The grouping by ["rep", "year", "month"] does all the work — pandas treats each unique combination as its own independent group.

Key insight

The power of multi-column grouping for period-to-date calculations is that adding "year" to the groupby ensures that January 2024 and January 2025 are treated as separate periods. If you only grouped by ["rep", "month"], your January 2025 rows would continue adding onto your January 2024 running total.

For YTD, just drop the month from the groupby:

df["rep_ytd_revenue"] = (
    df.groupby(["rep", "year"])["revenue"]
    .transform("cumsum")
)

Since our dataset only covers one year, this is equivalent to the overall running total — but in a multi-year dataset, YTD would reset each January.

You can also calculate region-level period-to-date metrics using the same pattern. If your manager wants to know how the East region is tracking MTD, just swap "rep" for "region":

df["region_mtd_revenue"] = (
    df.groupby(["region", "year", "month"])["revenue"]
    .transform("cumsum")
)

This is the kind of ranking and window calculation that would require a complex array formula in Excel but becomes almost mechanical in pandas once you understand the groupby + transform pattern.


Combining Metrics into a Report-Ready DataFrame

Now let's pull it all together into a clean output that you could send to a stakeholder or drop into a report.

# Start fresh with clean data
df_report = df[[
    "week", "rep", "region", "revenue",
    "rep_running_total",
    "rep_mtd_revenue",
    "rep_rolling_4w_avg",
    "above_rolling_avg"
]].copy()

# Round the rolling average for display
df_report["rep_rolling_4w_avg"] = df_report["rep_rolling_4w_avg"].round(0)

# Add a rank within each week — who had the most revenue that week?
df_report["weekly_rank"] = (
    df_report.groupby("week")["revenue"]
    .transform(lambda x: x.rank(ascending=False, method="min"))
    .astype(int)
)

print(df_report[df_report["rep"].isin(["Alice", "Bob"])].head(10))

This final weekly_rank column shows each rep's rank among all reps for that week, without collapsing the DataFrame. The same transform pattern handles it cleanly.

Tip

When you're building reports like this, consider adding a rep_pct_of_region_mtd column: df["rep_pct_of_region_mtd"] = df["rep_mtd_revenue"] / df["region_mtd_revenue"]. This immediately shows each rep's contribution to their region's month-to-date total — a metric that requires comparing two different levels of aggregation simultaneously, which is exactly where transform shines. For more patterns like this, see the article on Weighted Averages, Percent of Total, and Custom Aggregations in pandas.


Hands-On Exercise

Apply what you've learned on a slightly different dataset. Build a dataset of daily e-commerce orders for three product categories (Electronics, Clothing, Home Goods) across a full year (2024), with a random order value between $20 and $500 per day per category.

Your tasks:

  1. Calculate a 7-day rolling average order value for each category. Use min_periods=1 so the first 6 days still get a result.

  2. Calculate the MTD cumulative total order value per category, ensuring it resets at the start of each month.

  3. Add a column that shows each category's MTD total as a percentage of the overall MTD total across all categories for that same date. (Hint: calculate a total-MTD column across all categories first, then divide.)

  4. Find the 5 days where each category's daily order value was most above its 7-day rolling average. Sort your results by the difference, descending.

The goal is to practice combining groupby levels, transform, rolling, and expanding windows in a single analytical workflow.


Common Mistakes & Troubleshooting

"My running total doesn't reset between groups." This almost always means you forgot to include the grouping column in your groupby call, or you grouped by only one level when you needed two. For MTD, you need ["rep", "year", "month"] — not just ["rep", "month"].

"My rolling average is all NaN." Check that your data is sorted by date before calling rolling. An unsorted DataFrame won't necessarily throw an error — it will just produce NaN or nonsensical values. Also check that the window size isn't larger than the number of rows in your smallest group.

"I got a ValueError: transform must return a scalar or array with the same length as the group." This happens when your lambda function inside transform returns something unexpected — often a DataFrame instead of a Series. Make sure you're calling .mean(), .sum(), etc., at the end of your chain, and that you're operating on a single column (a Series), not the full grouped DataFrame.

"My period-to-date numbers look right for some reps but wrong for others." Sort your data before calculating. If one rep's rows are out of chronological order, their cumulative sum will be computed in the wrong sequence. Add df.sort_values(["rep", "week"], inplace=True) before any cumulative operation as a defensive habit.

Warning

Be careful about applying rolling across group boundaries. When you use groupby().transform(lambda x: x.rolling(n).mean()), the lambda receives each group's data independently, so the rolling window naturally can't reach back into the previous group's rows. But if you accidentally apply df["revenue"].rolling(4).mean() without groupby, the window will cross group boundaries — averaging the last week of Alice's data with the first weeks of Bob's. This is a silent bug that produces plausible-looking but incorrect numbers.

"I want to compare a value to the group's cumulative average, but expanding().mean() gives me NaN in the first row." The first row of an expanding().mean() returns that row's own value (a window of size 1 returns the single value). You'll only see NaN if there's a genuinely missing value in your data. Check for NaN in the source column with df["revenue"].isna().sum(). Refer to Cleaning Messy Data with pandas: Missing Values, Duplicates, and Data Types if you need to address upstream data quality issues.


Summary & Next Steps

Here's what you've built in this lesson:

  • Running totals by group using groupby().transform("cumsum"), which resets automatically for each group without any manual row detection
  • Moving averages by group using groupby().transform(lambda x: x.rolling(n).mean()), which smooths trends while respecting group boundaries
  • Period-to-date summaries (MTD, YTD) by including the period columns (year, month) in the groupby, so the cumulative total resets at the right boundary
  • Multi-level group metrics like region-level MTD, by simply changing which columns you include in the groupby

The unifying pattern is: groupby defines the boundary, transform keeps every row, the function inside does the math. Once that mental model clicks, you can apply it to dozens of different business questions without memorizing new methods.

Where to go from here:

  • For more window function patterns including percent rank and row numbering within groups, see Ranking and Window Calculations in pandas: Running Totals, Cumulative Averages, and Percent Rank with groupby and transform
  • To learn how to compare current-period values to prior periods — month-over-month growth rates, year-over-year changes — see Comparing Periods and Calculating Month-over-Month, Year-over-Year, and Rolling Changes in pandas with shift and pct_change
  • When you're ready to turn these metrics into a formatted Excel report, Automating Excel Reports with pandas and openpyxl shows you how to export a polished, formatted workbook without touching Excel manually
Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Python for Data Analysis

Previous

Building a Product Affinity and Basket Analysis Report in pandas: Calculating Co-Purchase Rates, Lift, and Frequently Bought Together Pairs from Transaction Line Items

Related Insights

PythonExpert

Building a Product Affinity and Basket Analysis Report in pandas: Calculating Co-Purchase Rates, Lift, and Frequently Bought Together Pairs from Transaction Line Items

23 min
PythonPractitioner

Building a Sales Funnel Analysis in pandas: Calculating Stage Conversion Rates, Drop-Off Points, and Pipeline Velocity from CRM Export Data

19 min
PythonFoundation

Unpivoting and Stacking Survey or Form Data in pandas: Transforming One-Row-Per-Respondent Wide Exports into Analysis-Ready Long Format

16 min

On this page

  • Introduction
  • Prerequisites
  • The Setup: A Realistic Dataset
  • Understanding transform: Why It's Different from agg
  • Running Totals by Group with cumsum
  • Moving Averages by Group with rolling
  • Period-to-Date Summaries: MTD and YTD
  • Combining Metrics into a Report-Ready DataFrame
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps