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 Fernhill 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 , each with revenue and spend :
where is the revenue attributed to row , is the spend of row , is the ROAS of that row on its own, and 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, , gives every row the weight 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
Fernhill 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: .
- Ratio of sums: .
The weights make the gap visible. Monday's weight is and Tuesday's is , so the weighted mean is
where the first term is Monday's weight times its ROAS of 20, and the second term is Tuesday's weight times its ROAS of 1.
Fernhill 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.
- 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
groupbydrops without a word. - 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".
- 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.
- Which clock, which revenue? The shop exports order times in UTC. Your month ends at midnight in the UK. 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. Fernhill Home is an online homeware shop in York (fernhillhome.example) selling candles, ceramics and textiles. Grace founded it, and Tariq 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 £58 and a gross margin of 52%. It sells through its own shop, runs Google Ads and Meta ads, and sends a newsletter. Tariq'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 Tariq 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.36, "paid_social": 0.23}
aov = {"organic_search": 57, "paid_search": 61, "paid_social": 50,
"email": 63, "direct": 60, "referral": 56}
# 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))
# 57.99
So Fernhill has 49,964 rows, 48,042 orders and 21,335 customers in 2024, with an average order value of £57.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 387216.13
# email 6975 405723.29
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 387216.13
# email 405723.29
# organic_search 780064.56
# paid_search 601182.58
# paid_social 319111.69
# referral 145317.21
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 £35,882
print(round(orders["revenue"].sum(), 2)) # total of the export
# 2674497.88
print(round(by_channel.sum(), 2)) # total of the channel table
# 2638615.46
print(orders.groupby("channel", dropna=False)["revenue"].sum().round(2).tail(2))
# channel
# referral 145317.21
# NaN 35882.42
The channel table is £35,882.42 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 Grace 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 780064.56 378.19 54.65
# paid_search 10253 8019 601182.58 485.98 58.63
# email 6709 5642 405723.29 452.40 60.47
# direct 6700 5639 387216.13 314.78 57.79
# paid_social 6716 5621 319111.69 292.69 47.52
# referral 2706 2495 145317.21 273.22 53.70
# (unknown) 685 675 35882.42 208.81 52.38
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 Tariq builds the report Grace 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. Fernhill's month ends at midnight in York. Between the last Sunday in March and the last Sunday in October, UK 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 York. Convert first, then take the month. GA4 already reports in the property's time zone, here Europe/London, 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 UK time before taking the month
local = orders["order_time"].dt.tz_convert("Europe/London").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 2104.41 NaN NaN
# direct 461 26600.43 16838.0 0.0
# email 490 30626.21 13432.0 0.0
# organic_search 995 54575.49 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 35882.42 NaN NaN 52.383 NaN NaN
# direct 6700 387216.13 0.00 0.029 57.793 NaN NaN
# email 6709 405723.29 0.00 0.037 60.474 NaN NaN
# organic_search 14273 780064.56 0.00 0.017 54.653 NaN NaN
# paid_search 10253 601182.58 149211.61 0.025 58.635 14.553 4.029
# paid_social 6716 319111.69 164986.60 0.009 47.515 24.566 1.934
# referral 2706 145317.21 0.00 0.019 53.702 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:
where is the number of distinct orders in the group, the number of sessions (visits), the revenue net of refunds and 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 pound spent. Paid social returns £1.93. With a gross margin of 52%, every pound of revenue leaves 52p to pay for the advertising, so the ROAS at which a channel just covers the cost of the goods it sells is
where 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 Tariq'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.85 3.92 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.
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 Grace. 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
Tariq 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": [940.00, 5310.40, 3050.20, 1986.19, 390.00, 11676.79],
"conv_value": [14100.00, 18586.40, 7625.50, 3177.90, 312.00, 43801.80],
})
ads["roas"] = ads["conv_value"] / ads["cost"]
print(ads.round(2))
# campaign cost conv_value roas
# 0 Brand 940.00 14100.0 15.00
# 1 Shopping candles 5310.40 18586.4 3.50
# 2 Shopping ceramics 3050.20 7625.5 2.50
# 3 Search textiles 1986.19 3177.9 1.60
# 4 Search competitor terms 390.00 312.0 0.80
# 5 Total 11676.79 43801.8 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())
# 23353.58
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 "Fernhill Home" would most likely have found the shop anyway, and the rest of the account returns 2.77.
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) 5726.84 0.014
# direct 58583.60 0.145
# email 60913.61 0.150
# organic_search 114439.48 0.282
# paid_search 95028.30 0.234
# paid_social 46665.95 0.115
# referral 24007.88 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 137213.47
208 customers placed ten or more orders in 2024, and between them brought £137,213.47, 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 Fernhill 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
Tariq 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) 51.47 48.52 51.04 49.12
# direct 56.09 55.19 55.85 55.81
# email 58.56 58.09 57.31 58.48
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) 7463.0 6842.0 6941.0 14636.0 35882.0
# direct 75157.0 76928.0 82385.0 152746.0 387216.0
# email 85211.0 81908.0 85164.0 153440.0 405723.0
# organic_search 157741.0 159354.0 169588.0 293382.0 780065.0
# paid_search 121324.0 120618.0 126903.0 232338.0 601183.0
# paid_social 64127.0 62671.0 69410.0 122904.0 319112.0
# referral 29636.0 29611.0 31464.0 54605.0 145317.0
# Total 540660.0 537932.0 571855.0 1024051.0 2674498.0
The bottom right cell, £2,674,498, 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.084 0.377 0.418 0.114 0.008
# paid_social 0.170 0.444 0.322 0.062 0.002
# email 0.082 0.366 0.421 0.122 0.009
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: 17.0% of its orders are under £25, twice the share 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
Grace 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 38219.88 0.014 17.910
# D2 2133 2241 75570.57 0.028 35.429
# D3 2134 2372 102143.31 0.038 47.865
# D4 2133 2693 131492.63 0.049 61.647
# D5 2134 3184 166242.49 0.062 77.902
# D6 2133 3801 209982.93 0.079 98.445
# D7 2133 4632 268343.16 0.100 125.806
# D8 2134 5819 349402.36 0.131 163.731
# D9 2133 7756 481822.26 0.180 225.889
# D10 2134 13341 851278.29 0.318 398.912
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 149211.61 32.32
# paid_social 2992 164986.60 55.14
Paid social costs £55.14 for each first order in 2024, against £32.32 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 Fernhill 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?
| Operation | Rows that come back | Typical marketing question | Watch out for |
|---|---|---|---|
agg with named aggregation | One per group | Orders, revenue and spend by channel and month | Build ratios after the sums, outside agg |
transform | One per input row | Share of the month, z score within a channel, first order time | The function must return one value per group or one per row |
filter | The rows of the groups that pass | Customers with ten or more orders | Slow with many groups, a transform mask is faster |
apply | Whatever the function returns | A small model per group | Slowest, pass include_groups=False in pandas 2.2 and later |
pivot_table | One per row key, one column per column key | Revenue by channel and quarter with totals | The default aggfunc is the mean, not the sum |
crosstab | Counts or shares per combination | Order value bands by channel | normalize decides what the shares add up to |
cumsum, cumcount, rolling | One per input row, in order | Order number, running revenue, seven day rate | Sort first, roll the sums, not the ratios |
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. Fernhill's channel table says paid social returns £1.93 per pound, 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 pound 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 Fernhill, the channel report built the honest way says that paid search returns £4.03 for every pound and paid social £1.93, at the break even line, with 17% of its orders under £25 and a cost per first order of £55.14. 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.
