Group by and pivot tables in pandas: from question to summary

TL;DR

Difficulty: Intermediate

Every grouped report splits a table into groups, applies a summary and combines the results. pandas does it with groupby and pivot_table.

  • Sum first, divide last: build ROAS, CPA, conversion rate and AOV from summed columns, never by averaging ratios. In the example, averaging campaign ROAS gives 4.68 when the real figure is 3.75.
  • Check that every summary adds back up to the total. groupby drops blank keys by default, and refund rows are not orders.
  • Use agg with named aggregation for summaries, transform for shares and z scores within groups, filter for whole groups, and apply only as a last resort.
  • pivot_table averages by default, unlike a spreadsheet. Pass aggfunc="sum".
  • qcut on ranks gives clean customer deciles.

A pivot table answers "revenue by channel" in a few clicks, and leaves no record of what it did. This chapter does the same in pandas, and goes further: named aggregation, shares and z scores within groups, deciles, running totals. Along the way it builds Ardmore Home's channel report with CPA, ROAS, conversion rate and AOV, computed the one way that does not mislead.

Sum first, divide last: the one rule behind every honest summary

Every business report is a set of questions of the same shape. Revenue by channel. Orders by month. Return on ad spend by campaign. Customers by how much they spend. A spreadsheet answers them with a pivot table. In pandas you answer them with groupby and pivot_table, and once you have the habit, you will answer them faster than you can drag fields into a box, with a record of exactly what you did.

But before any code, here is the rule that this whole chapter is built around, because it catches more wrong numbers in marketing reports than any other: sum first, divide last. Whenever the number you want is a ratio, such as return on ad spend (ROAS), conversion rate, cost per acquisition (CPA) or average order value (AOV), you add up the top and the bottom of the fraction within each group, and only then divide. You never average ratios that were already divided.

Why does it matter so much? Because an average of ratios gives every row the same vote, however small it is. A campaign that spent €10 counts exactly as much as a campaign that spent €10,000. The ratio of sums gives each row a vote in proportion to its size, which is what "the ROAS of this channel" actually means.

Here is the maths, in one line. For a set of rows i=1,…,ni = 1, \dots, n, each with revenue RiR_i and spend SiS_i:

ROAS=∑i=1nRi∑i=1nSi=∑i=1nwi RiSiwithwi=Si∑j=1nSj\text{ROAS} = \frac{\sum_{i=1}^{n} R_i}{\sum_{i=1}^{n} S_i} = \sum_{i=1}^{n} w_i \, \frac{R_i}{S_i} \quad \text{with} \quad w_i = \frac{S_i}{\sum_{j=1}^{n} S_j}

where RiR_i is the revenue attributed to row ii, SiS_i is the spend of row ii, RiSi\frac{R_i}{S_i} is the ROAS of that row on its own, and wiw_i is the row's share of total spend, its weight. The ratio of sums is a weighted mean of the row ratios, weighted by the denominator. The plain mean of ratios, 1n∑iRiSi\frac{1}{n}\sum_i \frac{R_i}{S_i}, gives every row the weight 1n\frac{1}{n} instead. The two agree only when every row has the same spend or the same ROAS. The difference between a simple and a weighted mean is set out in Foundations: the mean, and ratios themselves in Foundations: ratios and rates.

Example: two days of paid social

Ardmore Home, the example shop of this series, ran paid social for two days. On Monday it spent €10 and the shop attributed €200 of revenue to it, a ROAS of 20. On Tuesday it spent €990 and got €990 back, a ROAS of 1.

  • Mean of the two daily ratios: (20+1)/2=10.5(20 + 1) / 2 = 10.5.
  • Ratio of sums: (200+990)/(10+990)=1,190/1,000=1.19(200 + 990) / (10 + 990) = 1{,}190 / 1{,}000 = 1.19.

The weights make the gap visible. Monday's weight is 10/1,000=0.0110 / 1{,}000 = 0.01 and Tuesday's is 990/1,000=0.99990 / 1{,}000 = 0.99, so the weighted mean is

0.01×20+0.99×1=0.2+0.99=1.190.01 \times 20 + 0.99 \times 1 = 0.2 + 0.99 = 1.19

where the first term is Monday's weight w1=0.01w_1 = 0.01 times its ROAS of 20, and the second term is Tuesday's weight w2=0.99w_2 = 0.99 times its ROAS of 1.

Ardmore spent €1,000 and got €1,190 back. That is a ROAS of 1.19, which does not even cover the cost of the goods. The mean of ratios says 10.5, a number nobody would question if it sat in a dashboard. The rest of this chapter teaches the pandas tools, and every time a ratio appears, it will be built the honest way.

For the person who commissions this report

If you only read one section, read this one. You do not need to write the code to ask the four questions that tell you whether a grouped report can be trusted.

  1. Does it add up? Every breakdown, by channel, by month, by customer group, should add back to the total in the finance system. If the channel table sums to less than total revenue, rows have fallen out somewhere. In pandas the usual culprit is a blank channel, which groupby drops without a word.
  2. Were the ratios built from sums? Ask how ROAS, CPA, conversion rate and AOV were computed. The right answer is "total revenue divided by total spend, per channel". The wrong answer is "the average of the daily (or campaign) ROAS".
  3. What does one row mean? In a shop export, a refund is often its own row. Counting rows then counts refunds as orders. The report should count distinct order numbers.
  4. Which clock, which revenue? The shop exports order times in UTC. Your month ends at midnight in Ireland. A report that groups by UTC month moves late orders on the last day of a month into the wrong month, and an unclear revenue definition (with or without refunds, with or without VAT) moves every ratio.

A report that passes these four checks is worth discussing. One that fails any of them is worth fixing first, before anyone moves budget on it. The rest of the chapter shows each check in code, on data you can generate and run yourself.

The example shop, its data and its question

This series follows one invented business. Ardmore Home is an online homeware shop in Sligo (ardmorehome.example) selling candles, ceramics and textiles. Áine founded it, and Darragh is the analyst. The shop has about 1,200 products and about 48,000 orders a year from about 21,000 customers, an average order value of €66 and a gross margin of 52%. It sells through its own shop, runs Google Ads and Meta ads, and sends a newsletter. Darragh's standing question is the one this chapter moves forward: "Which channel really pays back, and what should we do with next month's budget?"

In the chapter on loading business data Darragh read the five exports into pandas. In the cleaning chapter he removed test and staff orders, and in the chapter on joining and reshaping he combined tables. Now he wants the summary: one row per channel and month, with the four ratios that matter.

So that you can run every line, the data is generated in code. The code below uses Python 3.13 with pandas 2.3 and NumPy 2.3, the current versions when this chapter was written12. If you set up your environment as in the setup chapter, you have everything you need.

Example: generating a year of traffic, spend and orders

The first table is daily: one row per day and channel for 2024, with sessions (from GA4), orders and, for the two paid channels, spend. The numbers are drawn at random around assumptions written at the top, so the shape is realistic: candles sell in autumn and before Christmas, paid social brings many visits that convert less often, email converts best.

import numpy as np
import pandas as pd

pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
rng = np.random.default_rng(2024)

days = pd.date_range("2024-01-01", "2024-12-31", freq="D")
channels = ["organic_search", "paid_search", "paid_social", "email", "direct", "referral"]

# Assumptions for the generated data: sessions per day, conversion rate,
# cost per session and average order value for each channel
base_sessions = {"organic_search": 2350, "paid_search": 1120, "paid_social": 1950,
                 "email": 510, "direct": 635, "referral": 390}
conv_rate = {"organic_search": 0.0165, "paid_search": 0.0245, "paid_social": 0.0094,
             "email": 0.0360, "direct": 0.0280, "referral": 0.0190}
cost_per_session = {"paid_search": 0.4097, "paid_social": 0.2617}
aov = {"organic_search": 64.86, "paid_search": 69.41, "paid_social": 56.90,
       "email": 71.69, "direct": 68.28, "referral": 63.72}

# Seasonality: candles sell in autumn and before Christmas
month_factor = np.array([0.85, 0.80, 0.85, 0.85, 0.85, 0.80,
                         0.80, 0.85, 0.95, 1.10, 1.45, 1.60])
season = month_factor[days.month - 1]

parts = []
for ch in channels:
    sessions = rng.poisson(base_sessions[ch] * season)
    cr = conv_rate[ch] * np.where(days.month >= 10, 1.12, 1.0)
    orders = rng.binomial(sessions, cr)
    spend = np.zeros(len(days))
    if ch in cost_per_session:
        spend = sessions * cost_per_session[ch] * rng.lognormal(0, 0.15, len(days))
    parts.append(pd.DataFrame({"date": days, "channel": ch, "sessions": sessions,
                               "orders": orders, "spend": spend.round(2)}))
daily = pd.concat(parts, ignore_index=True)

# Real tracking has incidents: a bot burst on the paid social landing page
bots = (daily["date"] == "2024-03-14") & (daily["channel"] == "paid_social")
daily.loc[bots, "sessions"] += 9000

print(daily.shape)
# (2196, 5)

The second table is the shop's order export, one row per order. It is built from the daily order counts, so the two tables agree. It carries the traps a real export carries: order times in UTC, a channel that is missing when the tracking parameters were lost, and refunds as separate rows with negative revenue.

# One row per order, from the daily order counts
orders = (daily.loc[daily.index.repeat(daily["orders"]), ["date", "channel"]]
          .reset_index(drop=True))
n = len(orders)
orders.insert(0, "order_id", np.arange(500001, 500001 + n))

# Order value: skewed, like real baskets
mean_value = orders["channel"].map(aov).to_numpy()
orders["revenue"] = rng.lognormal(np.log(mean_value) - 0.55**2 / 2, 0.55).round(2)

# The shop exports order time in UTC
seconds = pd.to_timedelta(rng.integers(0, 86400, n), unit="s")
orders["created_at_utc"] = (orders["date"] + seconds).dt.tz_localize("UTC")

# Customers: a few buy often, most buy once
propensity = rng.gamma(0.4, 1, 60000)
orders["customer_id"] = rng.choice(60000, size=n, p=propensity / propensity.sum()) + 100001

# The tracking parameters were lost on about 1.5% of orders: channel unknown
orders.loc[rng.random(n) < 0.015, "channel"] = np.nan
orders["row_type"] = "order"

# About 4% of orders are refunded in full, as a separate row
refunds = orders.sample(frac=0.04, random_state=7).copy()
refunds["revenue"] = -refunds["revenue"]
refunds["created_at_utc"] += pd.to_timedelta(rng.integers(3, 21, len(refunds)), unit="D")
refunds["row_type"] = "refund"

orders = (pd.concat([orders, refunds], ignore_index=True)
          .drop(columns="date")
          .sort_values("created_at_utc", ignore_index=True))

print(len(orders), orders["order_id"].nunique(), orders["customer_id"].nunique())
# 49964 48042 21335
print(round(orders.loc[orders["row_type"] == "order", "revenue"].mean(), 2))
# 65.99

So Ardmore has 49,964 rows, 48,042 orders and 21,335 customers in 2024, with an average order value of €65.99 before refunds. The 1,922 extra rows are refunds. Keep that difference in mind, because it is the first trap.

Split, apply, combine: what group by really does

Every grouped summary does the same three things. It splits the table into groups by the values of one or more key columns. It applies a function to each group separately. It combines the results into a new table with one row per group. Hadley Wickham named this pattern split, apply, combine in a 2011 paper and showed how many data analysis problems follow it3. The pandas user guide describes group by in exactly these three steps4. Wes McKinney's Python for Data Analysis gives the topic its own chapter5.

A pivot table in a spreadsheet is the same pattern behind a drag and drop screen: the row field splits, the summary function applies, the table combines. The difference in pandas is that each step is visible, and you can change any of them.

Example: revenue by channel, one step at a time

To see the three steps, you can loop over the groups yourself. A groupby object yields a pair for each group: the key and the rows that belong to it.

for name, group in orders.groupby("channel"):
    print(name, len(group), round(group["revenue"].sum(), 2))
    if name == "email":
        break
# direct 6946 440651.53
# email 6975 461687.65

That loop is split (the groups), apply (the sum per group) and combine (printing them in turn). You almost never write it this way, because pandas does all three in one line, much faster:

by_channel = orders.groupby("channel")["revenue"].sum()
print(by_channel.round(2))
# channel
# direct            440651.53
# email             461687.65
# organic_search    887631.98
# paid_search       684066.66
# paid_social       363149.51
# referral          165350.27

Read the line from left to right and it says what it does: take the orders, group them by channel, pick the revenue column, sum it. The result is a Series with the channel as its index, as explained in the chapter on Series and DataFrames.

Every summary must add back up to the total

Look at the table above again. Six channels. But the order export had a seventh value: the blank channel on orders whose tracking was lost. Where did it go?

By default, groupby drops every row whose group key is missing. The parameter is dropna, and its default is True6. No warning, no error. The revenue of those rows simply leaves the report. A spreadsheet pivot table at least shows a "(blank)" row. pandas does not.

That is why I check every grouped result with one rule before I look at a single number in it: the parts must add back up to the whole. If they do not, find out why before you go on.

Example: the missing €40,831

print(round(orders["revenue"].sum(), 2))    # total of the export
# 3043368.88
print(round(by_channel.sum(), 2))           # total of the channel table
# 3002537.6
print(orders.groupby("channel", dropna=False)["revenue"].sum().round(2).tail(2))
# channel
# referral    165350.27
# NaN          40831.28

The channel table is €40,831.28 short, exactly the revenue of the orders without a channel. With dropna=False they come back as their own group. Better still, give them a name you can read in a report, and make the check part of the code so it runs every time:

orders["channel"] = orders["channel"].fillna("(unknown)")
by_channel = orders.groupby("channel")["revenue"].sum()

# The reconciliation check: stops the notebook if rows went missing
assert np.isclose(by_channel.sum(), orders["revenue"].sum()), "summary does not reconcile"

An assert stops the code with an error when the condition is false. It costs one line and turns a silent loss into a loud one. The size of the unknown group is also worth reporting in its own right: 1.3% of revenue with no channel tells Áine how much she cannot attribute, which is a tracking job for the UTM tagging guide, not a rounding error.

Example: rows are not orders

The second way a summary stops adding up is a definition problem. Ask "how many orders per channel?" and the obvious code counts rows. But a refunded order has two rows: the sale and the refund.

rows = orders.groupby("channel").size()
real_orders = orders.groupby("channel")["order_id"].nunique()
print(pd.DataFrame({"rows": rows, "orders": real_orders, "difference": rows - real_orders}))
#                  rows  orders  difference
# channel
# (unknown)         720     685          35
# direct           6946    6700         246
# email            6975    6709         266
# organic_search  14838   14273         565
# paid_search     10675   10253         422
# paid_social      6997    6716         281
# referral         2813    2706         107

size() counts rows. nunique() counts distinct order numbers, so a refunded order counts once. Across the year the difference is 1,922 rows, 4% of orders. If you divide revenue by rows instead of orders, every channel's average order value comes out about 4% too low, and the CPA 4% too flattering.

There is a third groupby setting you should know before it surprises you: observed. It only matters when a key is a categorical column (you will make one with pd.cut later in this chapter). In pandas 2.3 the default is still observed=False, which keeps empty categories as rows of zeros, and pandas warns that the default will change to True in a future version6. Pass it explicitly and the warning, and the surprise, go away.

Several summaries at once: agg and named aggregation

One number per group is rarely enough. The agg method applies several functions in one pass. The clearest way to use it is named aggregation: each new column is written as name=(column, function), so the output columns have the names you chose instead of a stack of headers4.

Example: the channel summary in one call

summary = orders.groupby("channel").agg(
    orders=("order_id", "nunique"),
    customers=("customer_id", "nunique"),
    net_revenue=("revenue", "sum"),
    largest_order=("revenue", "max"),
)
summary["aov"] = summary["net_revenue"] / summary["orders"]   # sum first, divide last
print(summary.round(2).sort_values("net_revenue", ascending=False))
#                 orders  customers  net_revenue  largest_order    aov
# channel
# organic_search   14273      10250    887631.98         430.35  62.19
# paid_search      10253       8019    684066.66         552.98  66.72
# email             6709       5642    461687.65         514.81  68.82
# direct            6700       5639    440651.53         358.22  65.77
# paid_social       6716       5621    363149.51         333.08  54.07
# referral          2706       2495    165350.27         310.88  61.11
# (unknown)          685        675     40831.28         237.61  59.61

Notice what is not in the agg call: the average order value. It is a ratio, so it is computed after the sums, on the summary table. That habit of building the sums inside agg and the ratios outside it is the whole of "sum first, divide last" in pandas. It also means the AOV here is net of refunds. Revenue after refunds divided by orders placed is a choice, and a report should say so in a footnote.

The functions inside agg can be names pandas knows ("sum", "mean", "median", "min", "max", "size", "nunique", "first", "last", "std") or your own function. The named ones run in fast compiled code, so prefer them wherever they will do the job.

The channel report: CPA, ROAS, conversion rate and AOV by month

Now Darragh builds the report Áine asked for. It needs numbers from two sources: orders and revenue from the shop, sessions and spend from GA4 and the ad platforms. The plan is the rule again: sum each source to the same grain (month and channel), join the sums, then divide.

Example: putting each order in the right month

The shop export stores time in UTC. Ardmore's month ends at midnight in Sligo. Between the last Sunday in March and the last Sunday in October, Irish time is one hour ahead of UTC, so an order at 11.30pm UTC on 31 May was placed at half past midnight on 1 June in Sligo. Convert first, then take the month. GA4 already reports in the property's time zone, here Europe/Dublin, so its months are right as they are.

There is a second question: which month does a refund belong to? For a marketing report, the refund belongs to the month of the order it reverses, because the question is "what did that month's spend bring back?". transform, which you will meet properly in a moment, copies each order's first timestamp onto its refund row.

# The time of the order itself, copied onto its refund row as well
orders["order_time"] = orders.groupby("order_id")["created_at_utc"].transform("min")

# Convert to Irish time before taking the month
local = orders["order_time"].dt.tz_convert("Europe/Dublin").dt.tz_localize(None)
orders["month"] = local.dt.to_period("M")
orders["quarter"] = "Q" + orders["month"].dt.quarter.astype(str)

utc_month = orders["order_time"].dt.tz_localize(None).dt.to_period("M")
print((orders["month"] != utc_month).sum())
# 29

In this generated data, 29 rows change month. In a real shop the number is usually larger, because evening is when people shop. Twenty nine rows sounds small until the month in question is the one where a campaign launched. Time zones get their full treatment in the next chapter of this series, on time series.

Example: summing both sources to the same grain and joining them

shop = orders.groupby(["month", "channel"]).agg(
    orders=("order_id", "nunique"),
    revenue=("revenue", "sum"),
)
daily["month"] = daily["date"].dt.to_period("M")
traffic = daily.groupby(["month", "channel"])[["sessions", "spend"]].sum()

report = shop.join(traffic, how="left")
print(report.head(4))
#                         orders   revenue  sessions  spend
# month   channel
# 2024-01 (unknown)           42   2394.67       NaN    NaN
#         direct             461  30271.28   16838.0    0.0
#         email              490  34850.78   13432.0    0.0
#         organic_search     995  62101.14   61608.0    0.0

Grouping by two columns gives a MultiIndex: month on the outside, channel on the inside. The join matches rows on both levels, as in the joining chapter. The unknown channel has no sessions, because the shop cannot tell GA4 which visits those orders came from.

Example: the ratios, built from the sums

One small function adds the four ratios to any table that has the four sums. Because it only divides columns that are already sums, it works at any grain: month and channel, quarter and channel, or the whole year.

def add_ratios(t):
    t = t.copy()
    spend = t["spend"].where(t["spend"] > 0)      # no spend: no ROAS, not infinity
    t["conv_rate"] = t["orders"] / t["sessions"]
    t["aov"] = t["revenue"] / t["orders"]
    t["cpa"] = spend / t["orders"]
    t["roas"] = t["revenue"] / spend
    return t

year = add_ratios(report.groupby("channel").sum(min_count=1))
print(year[["orders", "revenue", "spend", "conv_rate", "aov", "cpa", "roas"]].round(3))
#                 orders    revenue      spend  conv_rate     aov     cpa   roas
# channel
# (unknown)          685   40831.28        NaN        NaN  59.608     NaN    NaN
# direct            6700  440651.53       0.00      0.029  65.769     NaN    NaN
# email             6709  461687.65       0.00      0.037  68.816     NaN    NaN
# organic_search   14273  887631.98       0.00      0.017  62.190     NaN    NaN
# paid_search      10253  684066.66  169811.03      0.025  66.719  16.562  4.028
# paid_social       6716  363149.51  187726.18      0.009  54.072  27.952  1.934
# referral          2706  165350.27       0.00      0.019  61.105     NaN    NaN

The annual table is built by summing the monthly sums again, and then dividing. Never build an annual ROAS by averaging the twelve monthly ROAS figures. With this data the two happen to land close together, because spend and revenue move together across the year. In your data they may not, and the method that is right by construction costs nothing extra.

The definitions, so the report can carry them in a footnote:

CR=OV,AOV=RO,CPA=SO,ROAS=RS\text{CR} = \frac{O}{V}, \qquad \text{AOV} = \frac{R}{O}, \qquad \text{CPA} = \frac{S}{O}, \qquad \text{ROAS} = \frac{R}{S}

where OO is the number of distinct orders in the group, VV the number of sessions (visits), RR the revenue net of refunds and SS the media spend, all summed over the same group of rows before dividing. The same four definitions sit behind Foundations: ratios and rates.

What does the table say? Paid search returns €4.03 for each euro spent. Paid social returns €1.93. With a gross margin of 52%, every euro of revenue leaves 52 cent to pay for the advertising, so the ROAS at which a channel just covers the cost of the goods it sells is

ROASbreak even=1m=10.52=1.92\text{ROAS}_{\text{break even}} = \frac{1}{m} = \frac{1}{0.52} = 1.92

where mm is the gross margin as a share of revenue. Paid social at 1.93 covers the goods and almost nothing else: not delivery, not payment fees, not the time spent running it. That is the first real answer to Darragh's standing question.

Example: the same channels, quarter by quarter

A year hides the seasons. The same function gives the quarterly view, again by summing first:

q = report.reset_index()
q["quarter"] = "Q" + q["month"].dt.quarter.astype(str)
quarterly = add_ratios(
    q.groupby(["channel", "quarter"])[["orders", "revenue", "sessions", "spend"]].sum()
)
roas_q = quarterly["roas"].dropna().unstack("quarter")
print(roas_q.round(2))
# quarter        Q1    Q2    Q3    Q4
# channel
# paid_search  3.75  3.84  3.91  4.37
# paid_social  1.88  1.84  1.89  2.04

unstack turns the inner index level, the quarter, into columns: the reshaping tool from the joining and reshaping chapter.

Grouped bar chart of ROAS by channel and quarter for Ardmore Home in 2024, an invented example. Paid search: Q1 3.75, Q2 3.84, Q3 3.91, Q4 4.37. Paid social: Q1 1.88, Q2 1.84, Q3 1.89, Q4 2.04. With a gross margin of 52%, the break even ROAS is 1.92, so paid social is below break even in the first three quarters and only just above it in the fourth. Every value is total revenue divided by total spend for the quarter. Tap or click to enlarge

Paid social is below the break even line of 1.92 in the first three quarters and only clears it before Christmas. That chart, with the break even line drawn on it, is the one to put in front of Áine. How to label it so the point lands is the subject of words on charts, and why a bar chart suits this comparison is in showing amounts and proportions.

The mean of ratios, caught in the act

The two days of paid social at the top of this chapter were small on purpose. Here is the same mistake in the form it usually takes: a column of ratios in an export, and an average at the bottom.

Example: the Google Ads campaign report

Darragh opens Google Ads' campaign report for September 2024. Each row has the campaign's cost and the conversion value Google Ads attributes to it, and the CSV ends with a totals row, as these reports do. The conversion value is the platform's own attribution, so it will not match the shop's figure for paid search exactly. For the arithmetic that does not matter.

# Google Ads campaign report, September 2024, as read from the CSV
ads = pd.DataFrame({
    "campaign": ["Brand", "Shopping candles", "Shopping ceramics",
                 "Search textiles", "Search competitor terms", "Total"],
    "cost": [1070.00, 6042.80, 3470.90, 2260.10, 444.00, 13287.80],
    "conv_value": [16050.00, 21149.80, 8677.25, 3616.16, 355.20, 49848.41],
})
ads["roas"] = ads["conv_value"] / ads["cost"]
print(ads.round(2))
#                   campaign     cost  conv_value   roas
# 0                    Brand   1070.0    16050.00  15.00
# 1         Shopping candles   6042.8    21149.80   3.50
# 2        Shopping ceramics   3470.9     8677.25   2.50
# 3          Search textiles   2260.1     3616.16   1.60
# 4  Search competitor terms    444.0      355.20   0.80
# 5                    Total  13287.8    49848.41   3.75

Two traps sit in this small table. The first is the totals row: sum the cost column as it is and you get twice the real spend. The second is the average of the ROAS column.

camp = ads[ads["campaign"] != "Total"]          # the totals row would double everything
print(ads["cost"].sum())
# 26575.6
print(round(camp["roas"].mean(), 2))             # mean of ratios: wrong
# 4.68
print(round(camp["conv_value"].sum() / camp["cost"].sum(), 2))   # ratio of sums: right
# 3.75
no_brand = camp[camp["campaign"] != "Brand"]
print(round(no_brand["conv_value"].sum() / no_brand["cost"].sum(), 2))
# 2.77

The mean of the five campaign ROAS figures is 4.68. The real ROAS of the account is 3.75. The small brand campaign, with 8% of the spend and a ROAS of 15, gets one fifth of the vote in the mean, and lifts it by almost a whole point. Take brand out, because people searching for "Ardmore Home" would most likely have found the shop anyway, and the rest of the account returns 2.77.

Bar chart of Ardmore Home's Google Ads ROAS for September 2024, an invented example. The mean of the five campaign ROAS figures is 4.68. The ratio of total conversion value to total cost is 3.75, the account's real ROAS. Without the brand campaign, the ratio of sums is 2.77. The mean of ratios overstates the real figure by 0.93 because the small brand campaign with a ROAS of 15 gets one fifth of the weight. Tap or click to enlarge

Example: the average conversion rate across channels

The same error hides in the shop's own data. Ask "what is our conversion rate?" and a quick answer averages the six channel rates from the annual table:

known = year.drop(index="(unknown)")
print(round(known["conv_rate"].mean(), 4))                          # mean of rates
# 0.0229
print(round(known["orders"].sum() / known["sessions"].sum(), 4))    # ratio of sums
# 0.0189

The mean of the channel rates says 2.29%. The shop actually converts 1.89% of its sessions. Email and direct, with high rates but few sessions, get the same vote as organic search and paid social, which bring most of the traffic. The overstatement is a fifth of the true figure. The same logic, applied to averages in general, is the subject of why averages mislead.

There are cases where a mean of ratios is the right question. If you want to know what a typical campaign achieves, regardless of size, an unweighted mean (or better, a median) answers that. But it is a different question from "what does our money return?", and the report should say which one it answers.

transform: a group result for every row

agg shrinks each group to one row. transform does the opposite: it computes a value per group and copies it back to every row of that group, so the result has the same length and index as the input. That makes it the tool for any question of the form "this row compared with its group": a share of the group total, a difference from the group average, a z score within the group4.

Example: each channel's share of its month

report["share_of_month"] = (report["revenue"]
                            / report.groupby(level="month")["revenue"].transform("sum"))
print(report.loc["2024-12", ["revenue", "share_of_month"]].round(3))
#                    revenue  share_of_month
# channel
# (unknown)          6516.66           0.014
# direct            66668.30           0.145
# email             69315.96           0.150
# organic_search   130219.88           0.282
# paid_search      108129.51           0.234
# paid_social       53105.81           0.115
# referral          27317.58           0.059

The transform("sum") gives every row its month's total revenue, and dividing turns revenue into a share. The check is built in: within every month the shares add up to exactly 1. Notice that groupby(level="month") groups by an index level instead of a column.

Example: z scores that find the bot day

A z score says how many standard deviations a value sits from its group's average. Here the group matters, because paid search and paid social convert at very different rates: a rate that is normal for one is an outlier for the other. Computing the z score within each channel compares every day with its own channel's days. The standard deviation itself is explained in Foundations: spread.

d = daily[daily["channel"].isin(["paid_search", "paid_social"])].copy()
d["cr"] = d["orders"] / d["sessions"]
g = d.groupby("channel")["cr"]
d["cr_z"] = (d["cr"] - g.transform("mean")) / g.transform("std")
print(d.loc[d["cr_z"].abs() > 3, ["date", "channel", "sessions", "orders", "cr", "cr_z"]].round(3))
#           date      channel  sessions  orders     cr   cr_z
# 805 2024-03-14  paid_social     10658      16  0.002 -3.619

One day out of 732 is more than three standard deviations away from its channel's normal: 14 March, when the bot burst sent 9,000 extra sessions to the paid social landing page and none of them bought anything. A z score is a daily check here, not a ratio for the report, so the mean of daily rates is fine for this purpose: each day is the unit you want to judge.

filter: keep or drop whole groups

filter decides about whole groups. You give it a function that receives each group and returns True or False, and it returns the rows of every group that passed, in their original shape.

Example: the customers who order ten times or more

big = orders.groupby("customer_id").filter(lambda g: g["order_id"].nunique() >= 10)
print(big["customer_id"].nunique(), round(big["revenue"].sum(), 2))
# 208 156138.35

208 customers placed ten or more orders in 2024, and between them brought €156,138.35, 5.1% of net revenue. The lambda is a small function written inline, as introduced in the Python basics chapter.

filter calls your function once per group, and Ardmore has 21,335 customers. The faster way to the same rows is transform and a mask:

n_orders = orders.groupby("customer_id")["order_id"].transform("nunique")
big = orders[n_orders >= 10]

Both give the same rows. The second runs the counting in compiled code and needs no Python function at all.

apply, and when to leave it alone

apply is the most flexible group operation. It hands each group to your function as a small DataFrame, and whatever your function returns (a number, a Series, a DataFrame) is stitched together into the result. McKinney calls it the general split, apply, combine5. It is also the slowest, because pandas has to call a Python function for every group and cannot guess what it will return.

Two notes for pandas 2.3. Since pandas 2.2, letting apply see the grouping columns themselves is deprecated, and pandas warns unless you pass include_groups=False7. And most things people use apply for can be written with agg or transform on a prepared column, which is the same vectorised idea as in the NumPy chapter.

Example: the email share of each customer's orders

Darragh wants, for each customer, the number of orders and the share of them that came through email. With apply:

sales = orders[orders["row_type"] == "order"]

def channel_mix(g):
    return pd.Series({"orders": len(g),
                      "share_email": (g["channel"] == "email").mean()})

slow = sales.groupby("customer_id").apply(channel_mix, include_groups=False)

And with a prepared column and named aggregation:

fast = (sales.assign(is_email=sales["channel"].eq("email"))
        .groupby("customer_id")
        .agg(orders=("order_id", "size"), share_email=("is_email", "mean")))
print(fast.head(3))
#              orders  share_email
# customer_id
# 100003            2     1.000000
# 100004            3     0.333333
# 100006            1     0.000000

The results are identical. When this code was run for the chapter, the apply version took several seconds and the agg version a few hundredths of a second, a difference of a couple of hundred times. The exact figure depends on the machine, the gap does not. The trick is the prepared column: a share of True values is the mean of a column of True and False, because Python counts True as 1. Keep apply for the rare question that really needs the whole group at once, such as fitting a small model per group.

pivot_table and crosstab: the spreadsheet view

pivot_table is groupby plus unstack in one call, with the vocabulary of a spreadsheet pivot table: index for the rows, columns for the columns, values for what to summarise, aggfunc for how, and margins for the totals row and column8.

There is one difference from a spreadsheet that catches almost everyone. In Excel, a numeric field dropped into the values area is summed by default9. In pandas, the default aggfunc of pivot_table is the mean8.

Example: the pivot table that quietly averages

pt_default = orders.pivot_table(index="channel", columns="quarter", values="revenue")
print(pt_default.round(2).head(3))
# quarter       Q1     Q2     Q3     Q4
# channel
# (unknown)  58.57  55.22  58.08  55.89
# direct     63.83  62.80  63.56  63.51
# email      66.64  66.10  65.22  66.54

These are averages of rows, refund rows included, which is to say not a number anyone asked for. They look plausible, which is the problem. Always pass aggfunc explicitly:

pt = orders.pivot_table(index="channel", columns="quarter", values="revenue",
                        aggfunc="sum", margins=True, margins_name="Total")
print(pt.round(0))
# quarter               Q1        Q2        Q3         Q4      Total
# channel
# (unknown)         8492.0    7785.0    7898.0    16655.0    40831.0
# direct           85529.0   87544.0   93754.0   173825.0   440652.0
# email            96965.0   93206.0   96911.0   174606.0   461688.0
# organic_search  179493.0  181328.0  192973.0   333838.0   887632.0
# paid_search     138051.0  137248.0  144398.0   264370.0   684067.0
# paid_social      72976.0   71320.0   78989.0   139864.0   363150.0
# referral         33722.0   33693.0   35802.0    62133.0   165350.0
# Total           615229.0  612124.0  650726.0  1165291.0  3043369.0

The bottom right cell, €3,043,369, is the export total, so the table reconciles. Q4 brings 38% of the year's revenue, the candle season in one number.

A warning about margins and ratios: the margins are computed by applying aggfunc to all the rows of that row or column. With aggfunc="sum" that is exactly right. If you ever pivot a column of ratios with aggfunc="mean", the margins are means of ratios, with every problem from the start of this chapter. Pivot the sums, then divide the pivoted tables.

pd.crosstab is the counting cousin: it cross tabulates two columns and counts how often each combination occurs. With normalize="index" each row is turned into shares that add up to 110.

cut and qcut: turning numbers into groups

Sometimes the group you want does not exist as a column yet. "Orders under €25" and "the top 10% of customers" are groups made from a number. pd.cut makes bins from edges you choose. pd.qcut makes bins from quantiles, so each bin holds the same number of rows11.

Example: order value bands by channel

bands = [0, 25, 50, 100, 200, np.inf]
labels = ["under 25", "25 to 50", "50 to 100", "100 to 200", "200 and over"]
sales = sales.assign(value_band=pd.cut(sales["revenue"], bins=bands,
                                       labels=labels, right=False))

share = pd.crosstab(sales["channel"], sales["value_band"], normalize="index")
print(share.round(3).loc[["paid_search", "paid_social", "email"]])
# value_band   under 25  25 to 50  50 to 100  100 to 200  200 and over
# channel
# paid_search     0.053     0.318      0.455       0.160         0.013
# paid_social     0.117     0.404      0.384       0.090         0.005
# email           0.051     0.312      0.445       0.175         0.017

right=False makes each band include its lower edge and exclude its upper one, so an order of exactly €25.00 lands in "25 to 50", which is how people read a band label. The result explains part of paid social's weak ROAS: 11.7% of its orders are under €25, more than twice the 5.3% of paid search. Paid social brings small first baskets. Whether those customers come back is a question for the deciles below and, later, for the lifetime value chapters of the marketing analytics series.

When you group by the band column, remember that it is categorical: pass observed=True so empty bands do not appear as zero rows, and so pandas 2.3 does not warn you about the coming change of default6.

band_revenue = sales.groupby("value_band", observed=True)["revenue"].sum()

Example: customer deciles by revenue, and the error you will hit first

Áine wants to know how concentrated revenue is: how much comes from the best customers. The standard answer is deciles: sort the customers by net revenue, cut them into ten groups of equal size, and sum each group. First the customer table:

cust = orders.groupby("customer_id").agg(orders=("order_id", "nunique"),
                                          net_revenue=("revenue", "sum"))
print(len(cust))
# 21335

Now the error everyone meets. Try deciles of order counts:

try:
    pd.qcut(cust["orders"], 10)
except ValueError as err:
    print(err)
# Bin edges must be unique: Index([1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 5.0, 22.0], ...

Almost half of the customers placed exactly one order, so the first five decile edges are all 1, and qcut cannot draw a boundary through a block of identical values. The same happens with revenue when many customers have the same value (zero, for the 416 customers whose only order was refunded). The fix is to rank first: rank(method="first") gives every customer a unique position, breaking ties by order of appearance, and qcut on the ranks makes ten groups of equal size.

cust["decile"] = pd.qcut(cust["net_revenue"].rank(method="first"), 10,
                         labels=[f"D{i}" for i in range(1, 11)])

dec = cust.groupby("decile", observed=True).agg(
    customers=("orders", "size"),
    orders=("orders", "sum"),
    net_revenue=("net_revenue", "sum"),
)
dec["revenue_share"] = dec["net_revenue"] / dec["net_revenue"].sum()
dec["revenue_per_customer"] = dec["net_revenue"] / dec["customers"]
print(dec.round(3))
#         customers  orders  net_revenue  revenue_share  revenue_per_customer
# decile
# D1           2134    2203     43491.42          0.014                20.380
# D2           2133    2241     85993.58          0.028                40.316
# D3           2134    2372    116231.30          0.038                54.466
# D4           2133    2692    149628.28          0.049                70.149
# D5           2134    3185    189170.83          0.062                88.646
# D6           2133    3801    238944.10          0.079               112.023
# D7           2133    4632    305353.39          0.100               143.157
# D8           2134    5819    397592.80          0.131               186.313
# D9           2133    7756    548275.80          0.180               257.044
# D10          2134   13341    968687.38          0.318               453.930
Bar chart of Ardmore Home's net revenue share by customer decile in 2024, an invented example, from the lowest spending tenth of customers (D1) to the highest (D10). D1 1.4%, D2 2.8%, D3 3.8%, D4 4.9%, D5 6.2%, D6 7.9%, D7 10.0%, D8 13.1%, D9 18.0%, D10 31.8%. The top two deciles together bring 49.8% of revenue. The top decile's 2,134 customers average €453.93 each, against €20.38 in the bottom decile. Tap or click to enlarge

The top 10% of customers, 2,134 people, bring 31.8% of net revenue, and the top 20% bring 49.8%. The bottom decile brings 1.4%. The revenue per customer column is, again, a ratio of sums. For how to chart a skewed distribution like this one honestly, see showing distributions.

One caution before this table goes into a deck. It covers one calendar year. A customer who joined in December and a customer who joined in January have had very different chances to spend, so some of the bottom deciles are new customers, not poor ones. Deciles by revenue describe the year. They do not yet say who is valuable, which is what segmentation and lifetime value do properly.

Running totals and rolling windows within groups

The last family of group operations keeps every row, like transform, but looks along the order of the rows: cumulative sums, counters, shifts and moving windows, each restarting at the start of every group.

Example: first orders and the cost of a new customer

cumcount numbers the rows within each group from zero. Sorted by time and grouped by customer, it gives each order its position in that customer's history, so order number 1 is a first order.

sales = sales.sort_values("created_at_utc")
sales["order_number"] = sales.groupby("customer_id").cumcount() + 1
sales["cum_revenue"] = sales.groupby("customer_id")["revenue"].cumsum()
sales["is_first"] = sales["order_number"] == 1

new = sales.groupby("channel").agg(first_orders=("is_first", "sum"))
new = new.join(year["spend"])
new["cost_per_new_customer"] = new["spend"].where(new["spend"] > 0) / new["first_orders"]
print(new.loc[["paid_search", "paid_social"]].round(2))
#              first_orders      spend  cost_per_new_customer
# channel
# paid_search          4616  169811.03                  36.79
# paid_social          2992  187726.18                  62.74

Paid social costs €62.74 for each first order in 2024, against €36.79 for paid search. If paid social's customers come back more often, that gap can close. If not, it confirms the ROAS table.

There is a trap in "first", and it is the one I would put on a sticky note: first in this export is not first ever. The data starts on 1 January 2024. A loyal customer whose first order of 2024 came in March has order number 1 here, even if she has bought from Ardmore since 2019. To count real new customers you need the full order history, or at least a year of history before the period you report on. The code is the same, the input is longer.

Example: a rolling conversion rate that stays honest

A seven day rolling window smooths daily noise. Here it is within each channel, and, because conversion rate is a ratio, it is built from rolling sums, not as a rolling mean of daily rates.

d = daily.sort_values(["channel", "date"]).copy()
roll = d.groupby("channel")[["sessions", "orders"]].transform(
    lambda s: s.rolling(7, min_periods=7).sum())
d["cr_7d"] = roll["orders"] / roll["sessions"]
print(d.loc[(d["channel"] == "paid_social")
            & d["date"].between("2024-03-12", "2024-03-21"),
            ["date", "sessions", "orders", "cr_7d"]].round(4))
#           date  sessions  orders   cr_7d
# 803 2024-03-12      1607      11  0.0096
# 804 2024-03-13      1633      13  0.0095
# 805 2024-03-14     10658      16  0.0053
# 806 2024-03-15      1658       8  0.0049
# 807 2024-03-16      1662      10  0.0044
# 808 2024-03-17      1599       9  0.0040
# 809 2024-03-18      1695      13  0.0039
# 810 2024-03-19      1637      17  0.0042
# 811 2024-03-20      1718      13  0.0042
# 812 2024-03-21      1709      19  0.0076

The bot day pulls the seven day rate down for exactly seven days and then drops out of the window. A rolling window shows you how long one bad day haunts a smoothed line. Rolling windows by date rather than by row count, and resampling to weeks and months, come in the next chapter, on time series.

Which group operation do I need?

Five methods cover almost every grouped question. The choice comes down to two questions: how many rows should come back, and does the answer need the whole group at once?

OperationRows that come backTypical marketing questionWatch out for
agg with named aggregationOne per groupOrders, revenue and spend by channel and monthBuild ratios after the sums, outside agg
transformOne per input rowShare of the month, z score within a channel, first order timeThe function must return one value per group or one per row
filterThe rows of the groups that passCustomers with ten or more ordersSlow with many groups, a transform mask is faster
applyWhatever the function returnsA small model per groupSlowest, pass include_groups=False in pandas 2.2 and later
pivot_tableOne per row key, one column per column keyRevenue by channel and quarter with totalsThe default aggfunc is the mean, not the sum
crosstabCounts or shares per combinationOrder value bands by channelnormalize decides what the shares add up to
cumsum, cumcount, rollingOne per input row, in orderOrder number, running revenue, seven day rateSort first, roll the sums, not the ratios
Tap or click to enlarge

My view: the summary is where marketing numbers go wrong

My view: most wrong numbers in marketing reports are not caused by bad data or bad models. They are caused at the summary step, by three habits that each look harmless. Averaging ratios that should have been built from sums. Grouping by a key with blanks in it and never checking the total. Counting rows and calling them orders. None of these throws an error, and every one of them makes a channel look better or worse than it is.

The fix is not cleverness. It is a short routine that runs every time: name the unknowns instead of dropping them, assert that the parts add up to the whole, count distinct orders, convert to local time before taking the month, and divide only at the end. Put those five lines into a function and the report carries its own audit.

The second part of my view is about what the summary is for. Ardmore's channel table says paid social returns €1.93 per euro, right at the break even line of 1.92, and only clears it before Christmas. That is an average return over a whole year of spend. It does not say what the next euro would return, which may be more or less than the average (the difference is set out in Foundations: marginal versus average). A grouped table tells you where to look. Deciding next month's budget needs the time series and the models that later chapters build on top of it. Analysis of this kind, from the export to the report a founder can act on, is a core part of my data science work.

Conclusion

Group by is the workhorse of business analysis, and pandas gives you the whole toolkit: groupby with agg and named aggregation for summaries, transform for shares and comparisons within groups, filter for whole groups, apply as the last resort, pivot_table and crosstab for the spreadsheet view, cut and qcut for bands and deciles, and cumulative and rolling operations within groups.

For Ardmore, the channel report built the honest way says that paid search returns €4.03 for every euro and paid social €1.93, at the break even line, with 11.7% of its orders under €25 and a cost per first order of €62.74. The top tenth of customers brings almost a third of revenue. The next chapter adds time properly: resampling, rolling windows by date and seasonality.

Whatever tool you use, the rule stays the same. Sum first, divide last, and check that the parts add up to the whole.

If you want a channel report that adds up and builds every ratio the honest way, book the free workshop: we go through your exports and your current report together, and the first two weeks of work are on me.

Sources

  1. 1.

    Python Software Foundation, Python 3.13.0 release, 7 October 2024, https://www.python.org/downloads/release/python-3130/

  2. 2.

    pandas release history (version 2.3.2 released 21 August 2025), Python Package Index, https://pypi.org/project/pandas/#history

  3. 3.

    Hadley Wickham, The split apply combine strategy for data analysis, Journal of Statistical Software, volume 40, issue 1, 2011, https://doi.org/10.18637/jss.v040.i01

  4. 4.

    pandas development team, Group by: split, apply, combine, pandas 2.3 user guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/groupby.html

  5. 5.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, chapter 10: Data Aggregation and Group Operations, free online edition, https://wesmckinney.com/book/data-aggregation

  6. 6.

    pandas development team, pandas.DataFrame.groupby (parameters dropna and observed), pandas 2.3 API reference, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.DataFrame.groupby.html

  7. 7.

    pandas development team, What's new in 2.2.0 (deprecation of including the groups in DataFrameGroupBy.apply), January 2024, https://pandas.pydata.org/pandas-docs/version/2.3/whatsnew/v2.2.0.html

  8. 8.

    pandas development team, pandas.pivot_table, pandas 2.3 API reference, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.pivot_table.html

  9. 9.

    Microsoft, Sum values in a PivotTable, Microsoft Support, https://support.microsoft.com/en-us/excel/sum-values-in-a-pivottable

  10. 10.

    pandas development team, pandas.crosstab, pandas 2.3 API reference, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.crosstab.html

  11. 11.

    pandas development team, pandas.cut and pandas.qcut, pandas 2.3 API reference, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.qcut.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter