Joining and reshaping data in pandas: merge, concat, pivot and melt, without a single row counted twice
TL;DR
Difficulty: Intermediate
Every join you mean as a lookup should add columns, never rows. Decide the grain first (one row per day per channel), build an empty spine of every combination, bring each source to that grain, and left join it on with validate and a control total.
- concat stacks tables of the same kind, after renaming to one vocabulary.
- merge puts different facts side by side. validate="many_to_one" stops a duplicated lookup that would have added £6,345 of invented spend.
- indicator=True shows what did not match: 46 orders with messy UTM tags, 43 paid orders without a campaign.
- Convert to the shop's time zone before taking the date: 110 orders sat on the wrong day.
- Keep data long while you compute, make it wide only for people to read: pivot, pivot_table, melt, stack, unstack.
Almost every marketing question needs data from more than one system, and joining it is where most reporting errors are born. This chapter builds a daily channel table from a shop export, GA4 and two ad platforms, step by step, and shows the checks that catch a duplicated lookup, a wrong time zone and a mismatched name before they reach a decision.
Every join should add columns, never rows
Here is the idea this whole chapter hangs on, so it goes first. When you join a lookup or a second source onto a table, you want new columns: the channel next to the campaign, the refund next to the order, the sessions next to the spend. You almost never want new rows. If the number of rows changes after a join you meant as a lookup, something in your keys is wrong, and every sum you take afterwards is wrong with it.
pandas will not warn you. A join that matches one row to two rows quietly copies the first row, and the spend on it, and the total goes up. Nothing crashes. The numbers simply look plausible and are not.
So I work to two rules, and the rest of this chapter is how to apply them:
- Decide the grain first. The grain is what one row means in the table you want at the end. For a channel report it is one row per day per channel. Every source is brought to that grain before it is joined, never after.
- Count rows and totals before and after every join. A lookup join keeps the row count. Additive totals (spend, revenue, sessions) survive every join unchanged. pandas can check the first for you with one argument,
validate, and you check the second with one line of arithmetic.
Example: the join that invented £6,345 of spend
Fernhill Home is the invented online shop that runs through this series: candles, ceramics and textiles from York, about 48,000 orders a year from about 21,000 customers, an average order value of £58 and a gross margin of 52%. The founder, Grace, asks her analyst, Tariq, the question she asks every month: "Which channel really pays back, and what should we do with next month's budget?"
Tariq stacks the Google Ads and Meta Ads reports for July 2025 into one table of 248 rows and £27,023.12 of spend. To label each campaign with its channel he joins a small campaign map that someone keeps in a spreadsheet. The result has 279 rows and £33,368.42 of spend. One campaign, Shopping All Products, sits in the map twice, so each of its 31 days was copied once. Paid search now shows £20,110 of spend instead of £13,765, its return on ad spend drops from 4.10 to 2.81, and its margin after ad costs falls from £15,582 to £9,237. A perfectly healthy channel suddenly looks like the place to cut.
With validate="many_to_one" the same join stops with an error before any of that happens. That one argument is the most valuable thing in this chapter, and I will come back to it with the full code.
If you only read one section
This part is for the person who commissions the analysis, a founder or a marketing manager, and who will skip the code.
Almost every marketing question needs data from more than one system: the shop knows the orders, Google Analytics 4 (GA4) knows the sessions, each ad platform knows its own spend. Combining them is called joining, and it is where most reporting errors are born, long before any chart or model. The errors are rarely dramatic. A campaign counted twice, orders after 11pm landing on the wrong day, refunds left out, a renamed campaign that quietly stops matching. Each one moves a channel's numbers by a few per cent or a few thousand pounds, which is exactly the size of the decisions you make with them.
You do not need to read code to protect yourself. Ask whoever builds the report five questions:
- What does one row of the final table mean? (A good answer: "one day and one channel".)
- Do the totals in the final table match the totals in each source? Spend should match the ad platforms to the penny, revenue should match the shop after refunds.
- Which rows did not match in each join, and what did you do with them?
- Which time zone is each source in, and which one did you convert to?
- Where the ad platform and the shop disagree on conversions, which number is in the report, and why?
If the answers come quickly and with numbers, the report is probably sound. If they do not, the report may still be right, but nobody can show it yet.
The four sources and the table you want
Before any code, write down what you have and what you want. This is the join plan, and it is the step most people skip.
Example: what the shop has for July
Tariq wants one table with one row per day and channel for July 2025, with spend, sessions, orders and revenue after refunds. Six channels: organic search, paid search, paid social, email, direct and referral. That is 31 days times 6 channels, so 186 rows. He knows the answer before he starts: the final table must have exactly 186 rows.
He has four sources, each already loaded as shown in the loading chapter of this series and cleaned of test orders and staff orders as in the cleaning chapter:
| Source | One row means | Join key | Trap |
|---|---|---|---|
| Shop order export | one order or one refund | order id, date, UTM medium | refunds as extra rows, times in UTC |
| GA4 export via BigQuery | one day and GA4 channel group | date, channel group | eight GA4 groups, not our six |
| Google Ads report | one day and campaign | date, campaign | one campaign runs on YouTube, not search |
| Meta Ads report | one day and campaign | date, campaign | spend in account currency, its own attribution |
Not one of the four sources is at the target grain. Every one has to be mapped to our channel names and summed to day and channel first. That is normal. The mistake is joining them as they come and hoping the grain sorts itself out.
Generate the example data
Every block from here on runs in order in one notebook. I tested the code with Python 3.13, pandas 2.3.2 (released on 21 August 2025)1 and NumPy 2.3.2. If you have not set these up yet, the setup chapter walks through it.
The data is invented and generated with a fixed seed, so you get exactly the numbers shown in the comments. The first block builds the shop's order export: about 131 orders a day, order times in UTC as the shop stores them, UTM tags (the campaign labels in a link, explained in the UTM tracking guide) with two kinds of messy tagging, and refunds as separate rows.
import numpy as np
import pandas as pd
rng = np.random.default_rng(2025) # fixed seed: same data on every run
TZ = "Europe/London" # the shop's own time zone
days = pd.date_range("2025-07-01", "2025-07-31", freq="D")
channels = ["organic_search", "paid_search", "paid_social",
"email", "direct", "referral"]
# orders per day, local hour of the order, channel and order value
n_per_day = rng.poisson(131, size=len(days))
n = n_per_day.sum()
hour_weight = np.array([3, 1, 1, 1, 1, 1, 2, 3, 4, 5, 5, 5,
6, 6, 5, 5, 5, 6, 7, 9, 10, 10, 8, 5], dtype=float)
hour = rng.choice(24, size=n, p=hour_weight / hour_weight.sum())
second = rng.integers(0, 3600, size=n)
local_ts = (pd.to_datetime(np.repeat(days.values, n_per_day))
+ pd.to_timedelta(hour, unit="h") + pd.to_timedelta(second, unit="s"))
channel = rng.choice(channels, size=n, p=[0.30, 0.24, 0.14, 0.12, 0.15, 0.05])
amount = np.round(rng.gamma(4.0, 58 / 4.0, size=n), 2)
# UTM tags as the shop records them, with two messy variants
medium_of = {"organic_search": "organic", "paid_search": "cpc",
"paid_social": "paid_social", "email": "email",
"direct": None, "referral": "referral"}
source_of = {"organic_search": "google", "paid_search": "google",
"paid_social": "facebook", "email": "newsletter",
"direct": None, "referral": "blog"}
utm_medium = np.array([medium_of[c] for c in channel], dtype=object)
utm_source = np.array([source_of[c] for c in channel], dtype=object)
utm_medium[(channel == "paid_social") & (rng.random(n) < 0.06)] = "paid-social"
utm_medium[(channel == "email") & (rng.random(n) < 0.03)] = "Email"
search_camps = ["brand_search", "generic_candles", "shopping_all_products", "ceramics_search"]
social_camps = ["prospecting_broad", "retargeting_7d", "catalogue_sales"]
utm_campaign = np.full(n, None, dtype=object)
ps, so = channel == "paid_search", channel == "paid_social"
utm_campaign[ps] = rng.choice(search_camps, size=ps.sum(), p=[0.22, 0.25, 0.38, 0.15])
utm_campaign[ps & (rng.random(n) < 0.03)] = "(not set)"
utm_campaign[so] = rng.choice(social_camps, size=so.sum(), p=[0.45, 0.35, 0.20])
orders = pd.DataFrame({
"order_id": np.arange(100001, 100001 + n),
"created_at": local_ts.tz_localize(TZ).tz_convert("UTC"), # stored in UTC
"type": "order",
"amount": amount,
"utm_source": utm_source,
"utm_medium": utm_medium,
"utm_campaign": utm_campaign,
})
# refunds: separate rows, days later, no UTM tags, negative amounts
ref = orders.sample(frac=0.06, random_state=1)
refunds = pd.DataFrame({
"order_id": ref["order_id"].values,
"created_at": ref["created_at"].values
+ pd.to_timedelta(rng.integers(2, 15, len(ref)), unit="D"),
"type": "refund",
"amount": -np.round(ref["amount"].values
* rng.choice([1.0, 0.5], len(ref), p=[0.7, 0.3]), 2),
})
refunds["created_at"] = pd.to_datetime(refunds["created_at"], utc=True)
shop_export = (pd.concat([orders, refunds], ignore_index=True)
.sort_values("created_at", ignore_index=True))
print(shop_export.shape) # (4303, 7)
print(shop_export["type"].value_counts()) # order 4059, refund 244
The export has 4,303 rows but only 4,059 orders. The other 244 rows are refunds. Count rows and you have counted refunds as sales, which is the first and most common trap in an order export.
The second block builds the two ad platform reports exactly as they arrive: different column names, a date as text in the Meta report, and spend in the account currency.
g_camps = ["Brand Search", "Generic Candles", "Shopping All Products",
"Ceramics | Search", "Demand Gen Summer"]
g_base = np.array([70, 110, 200, 60, 45]) # typical spend per day
google = pd.concat([
pd.DataFrame({"Day": days, "Campaign": c,
"Cost": (cost := np.round(b * rng.normal(1, 0.12, len(days)), 2)),
"Conversions": np.round(cost / 12.0 * rng.normal(1, 0.15, len(days)), 1)})
for c, b in zip(g_camps, g_base)], ignore_index=True)
m_camps = ["Prospecting Broad", "Retargeting 7d", "Catalogue Sales"]
m_base = np.array([190, 95, 90])
meta = pd.concat([
pd.DataFrame({"Reporting starts": days.strftime("%Y-%m-%d"),
"Campaign name": c,
"Amount spent (GBP)": (spent := np.round(b * rng.normal(1, 0.15, len(days)), 2)),
"Purchases": rng.poisson(spent / 13.0)})
for c, b in zip(m_camps, m_base)], ignore_index=True)
print(google.shape, meta.shape) # (155, 4) (93, 4)
The third block builds the GA4 sessions as a BigQuery query would return them, one row per day and GA4 channel group, with the date as text in GA4's YYYYMMDD form, and the newsletter tool's list of sends for later.
ga_groups = ["Organic Search", "Paid Search", "Paid Social", "Email",
"Direct", "Referral", "Organic Social", "Unassigned"]
ga_share = np.array([0.34, 0.20, 0.18, 0.07, 0.15, 0.03, 0.02, 0.01])
ga_rows = []
for d in days:
total = rng.normal(5200, 300)
s = np.round(total * ga_share * rng.normal(1, 0.06, len(ga_share))).astype(int)
ga_rows += [(d.strftime("%Y%m%d"), g, v) for g, v in zip(ga_groups, s)]
ga4 = pd.DataFrame(ga_rows, columns=["event_date", "channel_group", "sessions"])
sends = pd.DataFrame({
"sent_at": pd.to_datetime(["2025-07-03 08:00", "2025-07-08 08:00",
"2025-07-10 18:00", "2025-07-15 08:00",
"2025-07-17 18:00", "2025-07-22 08:00",
"2025-07-24 18:00", "2025-07-29 08:00"]),
"send": ["summer_candles", "new_ceramics", "weekend_edit", "linen_launch",
"weekend_edit_2", "garden_table", "weekend_edit_3", "last_chance_july"],
})
print(ga4.shape, ga4["sessions"].sum()) # (248, 3) 162513
Stacking tables of the same kind: concat
There are two ways to combine tables. You either put them on top of each other, because they hold the same kind of rows from different places, or you put them side by side, because they hold different facts about the same things. Stacking is pd.concat. Side by side is merge, which comes next. Wes McKinney's book covers both in its chapter on joining, combining and reshaping2, and the pandas user guide has the full reference3.
concat lines columns up by name, not by position. That is the whole trap: if Google calls it Cost and Meta calls it Amount spent (GBP), stacking them gives you two half empty columns instead of one full one. So you rename first, to one shared vocabulary, and stack second. The keys argument labels where each row came from, which you will want the first time a number looks odd.
Example: one spend table from two platforms
google_std = google.rename(columns={"Day": "date", "Campaign": "campaign",
"Cost": "spend", "Conversions": "platform_conv"})
meta_std = meta.rename(columns={"Reporting starts": "date", "Campaign name": "campaign",
"Amount spent (GBP)": "spend", "Purchases": "platform_conv"})
meta_std["date"] = pd.to_datetime(meta_std["date"]) # text to a real date
spend = (pd.concat([google_std, meta_std], keys=["google_ads", "meta_ads"],
names=["platform", None])
.reset_index(level="platform")
.reset_index(drop=True))
print(spend.shape) # (248, 5)
print(spend.groupby("platform")["spend"].sum())
# google_ads 15132.88
# meta_ads 11890.24
print(round(spend["spend"].sum(), 2)) # 27023.12
155 rows plus 93 rows make 248 rows, and £15,132.88 plus £11,890.24 make £27,023.12. Write those two numbers down. They are the control totals every later step must reproduce.
Two details matter here. First, the Meta date was text, and text dates never match real dates in a join, so convert before, not after. Second, the spend is only comparable because both accounts bill in pounds. A Meta account set up in another currency reports spend in that currency, and the conversion belongs in this step, before the stack, at the rate for each day.
Joining side by side: merge and its four kinds
merge matches rows from two tables on one or more key columns and puts their columns side by side, the same idea as a JOIN in SQL. The how argument decides what happens to rows that find no partner. The pandas reference lists five options4. Four are everyday ones. The fifth, cross, pairs every row with every row, and the spine section below uses it on purpose.
| how | Keeps | Unmatched rows | Use it for |
|---|---|---|---|
inner (the default) | only keys found in both tables | dropped without a word | comparing two complete lists |
left | every row of the left table | left rows get empty values | adding a lookup to your main table |
right | every row of the right table | right rows get empty values | rarely: swap the tables and use left |
outer | every key from either table | both sides kept, gaps empty | reconciling two sources |
cross | every combination of rows | not applicable | building a spine of dates times channels |
The default is inner, and that is a quiet risk for reporting. An inner join drops every row that does not match, and a report that drops rows looks exactly like a report that had fewer of them. For a lookup, I always write how="left" explicitly, then check what did not match.
Keys come in two forms. on="date" when the column has the same name on both sides, left_on and right_on when the names differ. Several keys go in a list, on=["date", "channel"], and then a row matches only when every key matches.
Example: what each kind does to six orders
A small case makes the table above concrete. Six orders carry a UTM medium, and a lookup knows four mediums.
few = pd.DataFrame({"order_id": [1, 2, 3, 4, 5, 6],
"utm_medium": ["cpc", "email", "paid-social", "organic", "cpc", "tiktok"]})
lookup = pd.DataFrame({"utm_medium": ["cpc", "email", "organic", "referral"],
"channel": ["paid_search", "email", "organic_search", "referral"]})
for how in ["inner", "left", "outer"]:
print(how, len(few.merge(lookup, on="utm_medium", how=how)))
# inner 4 (orders 3 and 6 vanish)
# left 6 (orders 3 and 6 kept, channel empty)
# outer 7 (plus the unused 'referral' row from the lookup)
The inner join loses a third of the orders and says nothing. The left join keeps every order and leaves two holes you can see. The outer join also shows the lookup row nobody used. That is why a lookup is a left join, and why the next two arguments exist.
validate: the argument that catches a join explosion
A join explosion happens when a key you believed was unique is not. If an order's key matches rows in the lookup, that order appears times in the result. The number of rows after a left join is
where is the number of rows in the left table, is the number of rows in the right table whose key matches row , and is the number of rows in the result. When every is 0 or 1, , which is the row count contract. One key with adds a row, and copies every number on it. The ratio is the explosion factor: in the example below it is , so one row in eight is a copy (Foundations: ratios and rates).
The validate argument tells pandas what relationship you expect, and it raises an error if the data disagrees4. The four settings:
"one_to_one"(or"1:1"): keys unique on both sides. Use it when joining two tables at the same grain, such as sources onto the spine."many_to_one"(or"m:1"): many rows on the left may share a key, but the right side must be unique. This is every lookup."one_to_many"(or"1:m"): the mirror image."many_to_many": allowed, and checks nothing.
Example: the duplicated campaign map
Fernhill's campaign map tells Tariq which channel each campaign belongs to. It exists because a platform is not a channel: Demand Gen Summer runs inside Google Ads but shows on YouTube and in feeds, and Grace counts it as paid social. The map also has a product line column, and that is where the duplicate came from: someone added Shopping All Products a second time with "candles" when they planned a split that never happened.
campaign_map = pd.DataFrame({
"campaign": ["Brand Search", "Generic Candles", "Shopping All Products",
"Ceramics | Search", "Demand Gen Summer", "Prospecting Broad",
"Retargeting 7d", "Catalogue Sales", "Shopping All Products"],
"channel": ["paid_search", "paid_search", "paid_search", "paid_search",
"paid_social", "paid_social", "paid_social", "paid_social",
"paid_search"],
"product_line": ["all", "candles", "all", "ceramics", "all", "all",
"all", "all", "candles"],
})
bad = spend.merge(campaign_map, on="campaign", how="left")
print(len(spend), "->", len(bad)) # 248 -> 279
print(round(bad["spend"].sum(), 2)) # 33368.42, not 27023.12
Now the same join with the expectation written down:
try:
spend.merge(campaign_map, on="campaign", how="left", validate="many_to_one")
except pd.errors.MergeError as e:
print(e)
# Merge keys are not unique in right dataset; not a many-to-one merge
print(campaign_map[campaign_map.duplicated("campaign", keep=False)])
# campaign channel product_line
# 2 Shopping All Products paid_search all
# 8 Shopping All Products paid_search candles
The error names the problem, and duplicated(keep=False) shows both offending rows. Which one to keep is a business decision, not a coding one. Here the split never happened, so the first row is right. Fix the map, join again with the check in place, and confirm the control total:
campaign_map = campaign_map.drop_duplicates("campaign", keep="first")
spend = spend.merge(campaign_map, on="campaign", how="left",
validate="many_to_one", indicator=True)
print(spend["_merge"].value_counts().to_dict())
# {'both': 248, 'left_only': 0, 'right_only': 0}
assert len(spend) == 248 and round(spend["spend"].sum(), 2) == 27023.12
spend = spend.drop(columns="_merge")
spend_daily = (spend.groupby(["date", "channel"], as_index=False)
.agg(spend=("spend", "sum"), platform_conv=("platform_conv", "sum")))
print(spend_daily.shape) # (62, 4)
248 rows in, 248 rows out, £27,023.12 in, £27,023.12 out. Summed to day and channel, the spend table now has 62 rows: 31 days for paid search and 31 for paid social. It is at the target grain and ready to join.
A practical note on cost. validate checks uniqueness, which takes a moment on very large tables. On a few million rows it still costs far less than a board meeting about a wrong number, so I leave it on everywhere.
indicator: see exactly what did not match
validate catches too many matches. indicator=True shows too few. It adds a column called _merge that says, for each row, whether its key was found in both tables, only in the left one (left_only) or only in the right one (right_only)4. On a left join, every left_only row is a row your lookup could not label.
One more behaviour to know before the example. pandas matches missing keys with each other: if both tables have a row whose key is empty, those rows join, which is different from SQL, where an empty key never matches anything4. So never leave the empty value to chance. Give it an explicit label first.
Example: labelling orders with their channel
The shop's order rows carry a UTM medium. A lookup of six mediums turns them into channels. Direct orders have no medium at all, so Tariq labels them (none) first, the label GA4 also uses for direct traffic.
sales = shop_export[shop_export["type"] == "order"].copy()
refund_rows = shop_export[shop_export["type"] == "refund"].copy()
medium_map = pd.DataFrame({
"utm_medium": ["organic", "cpc", "paid_social", "email", "referral", "(none)"],
"channel": ["organic_search", "paid_search", "paid_social", "email",
"referral", "direct"],
})
sales["utm_medium"] = sales["utm_medium"].fillna("(none)")
check = sales.merge(medium_map, on="utm_medium", how="left",
validate="many_to_one", indicator=True)
print(check["_merge"].value_counts().to_dict())
# {'both': 4013, 'left_only': 46, 'right_only': 0}
print(check.loc[check["_merge"] == "left_only", "utm_medium"].value_counts())
# paid-social 34
# Email 12
46 orders, worth £2,766.56 before refunds, would have landed in no channel at all. Under an inner join they would simply be gone. The cause is ordinary: an old link template with a hyphen and a capital E typed by hand. The fix is to normalise the key on the data side, then run the same check again until nothing is left over:
sales["utm_medium"] = (sales["utm_medium"].str.lower()
.str.replace("-", "_", regex=False))
sales = sales.merge(medium_map, on="utm_medium", how="left",
validate="many_to_one", indicator=True)
assert (sales["_merge"] == "both").all()
sales = sales.drop(columns="_merge")
print(sales["channel"].value_counts().to_dict())
# {'organic_search': 1236, 'paid_search': 1000, 'paid_social': 581,
# 'direct': 574, 'email': 472, 'referral': 196}
The assert line matters more than it looks. It turns "I checked it once" into "the notebook refuses to continue if it ever happens again", and the final chapter of this series, on a reproducible workflow, turns habits like this into proper tests.
Time zones decide which day an order belongs to
Before orders can join anything by date, they need the right date. The shop stores order times in Coordinated Universal Time (UTC). Fernhill's business day runs on London time, which in July is one hour ahead of UTC. An order placed at 12.30am on 2 July in York is stored as 11.30pm on 1 July. Take the date straight from the stored time and that order lands on the wrong day.
GA4 is different again. In the BigQuery export, event_date is the date in the property's own time zone, while event_timestamp is in UTC5. So GA4's dates are already London dates, and the shop's are not. Join them without converting and you compare two different days on every row near midnight.
Example: 110 orders on the wrong day
wrong = sales["created_at"].dt.tz_convert(None).dt.normalize() # UTC date
sales["date"] = (sales["created_at"].dt.tz_convert(TZ) # London time
.dt.tz_localize(None).dt.normalize()) # London date
print((wrong != sales["date"]).sum()) # 110
print((wrong < "2025-07-01").sum()) # 3 July orders dated 30 June
110 of 4,059 orders, 2.7%, sit on the wrong day if you use the UTC date. Three of them even fall out of July. For a monthly total that is small. For a daily chart, or a day of the week analysis, or a test that ran from Monday to Sunday, it is not: the late evening is when this shop sells most, so the error piles up on the busiest hours. The rule is to convert every timestamp to the business's time zone first, and take the date second. The chapter on time series later in this series goes deeper into time zone aware data.
Ad platforms add one more layer: each account reports in the time zone it was set up with. Check it once in each account's settings and write it next to the join plan. If one account runs on a different zone, its days cut at a different midnight, and no join can repair that after the fact.
Refunds belong to the order they reverse
The export lists refunds as their own rows, dated when the money went back, without any UTM tags. There are two honest ways to count them. Deduct refunds on the day they happen, which matches the bank account. Or deduct them from the original order, which tells you what each channel's orders were really worth. For "which channel pays back" the second is the right one: a channel that brings orders that come back is worth less, and the refund row itself does not know which channel it belongs to. Only the order does.
Example: joining 244 refund rows back to their orders
A refunded order can have more than one refund row (a partial refund, then the rest), so the refunds are summed per order first. That makes the refund table unique per order, which validate="one_to_one" then proves.
refund_per_order = (refund_rows.groupby("order_id", as_index=False)["amount"].sum()
.rename(columns={"amount": "refunded"}))
n_before = len(sales)
sales = sales.merge(refund_per_order, on="order_id", how="left", validate="one_to_one")
assert len(sales) == n_before # still 4059 rows
sales["refunded"] = sales["refunded"].fillna(0.0) # no refund row means nothing refunded
sales["net_revenue"] = sales["amount"] + sales["refunded"]
print(round(sales["amount"].sum(), 2)) # 236587.87 gross
print(round(sales["refunded"].sum(), 2)) # -11936.95 refunded
print(round(sales["net_revenue"].sum(), 2)) # 224650.92 net
Notice the fillna(0.0). A missing refund after a left join genuinely means "no refund", so zero is the truth. That is not always so, and the spine section below comes back to when a gap may be filled with zero and when it may not.
Now the shop data can be summed to the grain:
shop_daily = (sales.groupby(["date", "channel"], as_index=False)
.agg(orders=("order_id", "nunique"), revenue=("net_revenue", "sum")))
print(shop_daily.shape) # (186, 4)
Mismatched names: build a key, then report what is left
Joining spend to orders by campaign is the classic marketing join, and it fails for a boring reason: the names are typed by different people in different tools. Google Ads says Ceramics | Search, the link says ceramics_search. The fix is a key function that turns both into the same plain form, applied to both sides, and an outer join with indicator to report what still does not match.
Example: spend and orders by campaign for July
def campaign_key(s):
"""lower case, and any run of spaces, signs or underscores becomes one underscore"""
return s.str.lower().str.replace(r"[\W_]+", "_", regex=True).str.strip("_")
camp_spend = (spend.assign(key=campaign_key(spend["campaign"]))
.groupby("key", as_index=False)["spend"].sum())
camp_orders = (sales[sales["channel"].isin(["paid_search", "paid_social"])]
.assign(key=lambda d: campaign_key(d["utm_campaign"].fillna("(not set)")))
.groupby("key", as_index=False)
.agg(orders=("order_id", "nunique"), revenue=("net_revenue", "sum")))
camp = camp_spend.merge(camp_orders, on="key", how="outer",
validate="one_to_one", indicator=True)
print(camp.round(0))
# key spend orders revenue _merge
# 0 brand_search 2145.0 200.0 11445.0 both
# 1 catalogue_sales 2919.0 98.0 5735.0 both
# 2 ceramics_search 1891.0 148.0 8808.0 both
# 3 demand_gen_summer 1368.0 NaN NaN left_only
# 4 generic_candles 3384.0 251.0 13850.0 both
# 5 not_set NaN 43.0 2516.0 right_only
# 6 prospecting_broad 5992.0 269.0 15014.0 both
# 7 retargeting_7d 2979.0 214.0 12053.0 both
# 8 shopping_all_products 6345.0 358.0 19817.0 both
Seven campaigns match. Two rows tell a story of their own, and they are why I use an outer join here rather than a left one. Demand Gen Summer spent £1,368 and has no tagged orders: its links were never given UTM tags, or its buyers came back later through another route. Either way that is a finding for Grace, not a coding error. And 43 paid search orders, worth £2,516, carry (not set) as their campaign: they reached the shop through a paid click without a readable campaign name. They are paid search orders, so they count in the channel table, but no single campaign can claim them.
An inner join would have hidden both rows. That is the difference between a report that looks tidy and one that is complete.
Platform numbers and shop numbers sit side by side, never added
Each ad platform counts conversions by its own rules: its own attribution window (how many days after a click or a view it still claims a purchase), its own model, its own view of which device belongs to whom. The shop counts orders by the UTM tag on the visit that bought. Neither is wrong. They answer different questions. What you must never do is add them up or put one where the other belongs.
So in the daily table both columns sit side by side: platform_conv from the ad report, orders from the shop. A join is how you compare them, not how you merge them into one number.
Example: what the platforms claim against what the shop recorded
For July, Google Ads claims 1,127 conversions for the search campaigns. The shop recorded 1,000 paid search orders. Meta, together with the Demand Gen campaign, claims 987 purchases. The shop recorded 581 paid social orders. Google's count is 13% higher than the shop's, the social platforms' is 70% higher.
A gap like this is normal. A platform counts over its own window of days after a click, the Meta report states the attribution setting it used, and if that setting includes views, a purchase can count after someone only saw an ad. Google Ads also adds modelled conversions where it cannot observe one directly6. The shop's count by UTM tag, for its part, credits only the visit that bought, so it undercounts channels that start journeys others finish. Which number to plan with is the question of attribution, and the honest answer usually lies between the two and needs an experiment to pin down. For this chapter the point is narrower: the join must keep both numbers visible. A report with only the platform's number flatters paid social by about 70%.
Build the daily channel table on a spine
Now everything comes together. The spine is an empty table with one row for every combination the final table must have: 31 days times 6 channels. Every source is left joined onto it. This has two advantages over joining sources onto each other. Days with no spend or no orders still appear (a missing row and a zero are different things, and a chart of missing rows lies), and the row count stays fixed at 186 no matter what any source does, so validate="one_to_one" on each join proves that nothing was duplicated.
Example: four sources onto 186 rows
First the GA4 sessions need our channel names. GA4 has eight channel groups in this export, and two of them, Organic Social and Unassigned, are not among Fernhill's six channels.
ga_names = {"Organic Search": "organic_search", "Paid Search": "paid_search",
"Paid Social": "paid_social", "Email": "email",
"Direct": "direct", "Referral": "referral"}
sessions_daily = ga4.assign(
date=pd.to_datetime(ga4["event_date"], format="%Y%m%d"),
channel=ga4["channel_group"].map(ga_names),
)
left_out = sessions_daily[sessions_daily["channel"].isna()]
print(left_out.groupby("channel_group")["sessions"].sum().to_dict())
# {'Organic Social': 3250, 'Unassigned': 1588}
sessions_daily = sessions_daily.dropna(subset=["channel"])[["date", "channel", "sessions"]]
4,838 of 162,513 sessions, about 3%, fall outside the six channels. Dropping them is a decision, so it is printed and written down, not left to an inner join to do silently. If organic social grows, it earns its own row in the channel list.
Then the spine and the three joins:
spine = (pd.MultiIndex.from_product([days, channels], names=["date", "channel"])
.to_frame(index=False))
daily = spine
for name, part in [("spend", spend_daily), ("sessions", sessions_daily),
("orders", shop_daily)]:
daily = daily.merge(part, on=["date", "channel"], how="left", validate="one_to_one")
print(name, len(daily))
# spend 186
# sessions 186
# orders 186
daily = daily.fillna({"spend": 0.0, "platform_conv": 0.0, "orders": 0, "revenue": 0.0})
daily["orders"] = daily["orders"].astype(int)
MultiIndex.from_product builds every combination of the two lists. merge(how="cross") between a table of dates and a table of channels does the same thing.
The fillna deserves a second look. Organic search has no spend because it costs nothing in ads, so zero is true. A day with no orders from referral had zero orders, so zero is true. But a day missing from the GA4 export because the export failed did not have zero sessions, it has unknown sessions, and filling it with zero would invent a bad day. That is why sessions is not in the fillna list: if it ever has a gap, the gap should stay visible.
Last, the control totals. Every additive number in the final table must equal its source:
assert round(daily["spend"].sum(), 2) == round(spend["spend"].sum(), 2) # 27023.12
assert round(daily["revenue"].sum(), 2) == round(sales["net_revenue"].sum(), 2) # 224650.92
assert daily["sessions"].sum() == sessions_daily["sessions"].sum() # 157675
assert daily["orders"].sum() == len(sales) # 4059
print(daily.head(3))
# date channel spend platform_conv sessions orders revenue
# 0 2025-07-01 organic_search 0.00 0.0 1803 47 2318.52
# 1 2025-07-01 paid_search 417.54 28.5 967 30 1723.56
# 2 2025-07-01 paid_social 478.41 35.1 967 20 1460.81
Every join kept its row count except the broken one. That chart, or the printout behind it, is the evidence that the table is sound, and it is worth keeping in the notebook for whoever checks the work next.
The answer to Grace's question
With the table built, the question takes a few lines. Summing to channel level is the subject of the next chapter, on group by and pivot tables, so here it is kept short.
Return on ad spend (ROAS) is revenue divided by ad spend. With a gross margin of 52%, a channel only pays back if its revenue covers the ad cost out of the margin it earns:
where is revenue after refunds, is ad spend, is the gross margin as a share (0.52), and is the margin left after ad costs. The break even ROAS here is : below it, each pound of ads returns less than a pound of margin. For paid search, and , so ROAS is and . Foundations: ratios and rates explains ratios like this one from scratch.
Example: the July channel summary
month = daily.groupby("channel").agg(spend=("spend", "sum"), sessions=("sessions", "sum"),
orders=("orders", "sum"), revenue=("revenue", "sum"),
platform_conv=("platform_conv", "sum"))
month["roas"] = (month["revenue"] / month["spend"].where(month["spend"] > 0)).round(2)
month["margin_after_ads"] = (0.52 * month["revenue"] - month["spend"]).round(0)
print(month.loc[["paid_search", "paid_social"],
["spend", "orders", "revenue", "roas", "margin_after_ads"]]
.round({"spend": 0, "revenue": 0}))
# spend orders revenue roas margin_after_ads
# paid_search 13765.0 1000 56437.0 4.10 15582.0
# paid_social 13258.0 581 32801.0 2.47 3798.0
On the shop's own count, paid search returns 4.10 and leaves £15,582 of margin after its ad costs. Paid social returns 2.47, above the break even of 1.92, and leaves £3,798. Both pay back. Paid search pays back far better per pound. Had Tariq used the broken campaign map, paid search would have shown 2.81 and Grace might have moved money the wrong way.
What this table cannot say is what would happen to orders if a channel's budget moved, because last click revenue is not the same as the revenue a channel causes. That is the work of experiments and models in later parts of this programme. But it is now a table that is right about what happened, and every model needs that first.
Different frequencies: merge_asof and choosing the coarser grain
Not every source arrives at the same frequency. Sessions are daily, a newsletter goes out a few times a month, a budget plan is monthly, an agency invoice may be weekly. Two tools cover most cases.
When one source is coarser than the other, bring the finer one up to the coarser grain, never the other way round. Summing daily spend to months is exact. Spreading a monthly budget evenly over 31 days invents a daily pattern that never existed. If you must spread, label the column as an assumption.
When the question is "which event came just before this one", use pd.merge_asof. It joins each row of the left table to the nearest earlier (or later) row of the right table by time, rather than requiring an exact match7. Both tables must be sorted by their time column. direction="backward" looks for the most recent earlier row, and tolerance sets how far back it may look.
Example: which newsletter did each email order follow?
email_orders = (sales[sales["channel"] == "email"]
.assign(ordered_at=lambda d: d["created_at"].dt.tz_convert(TZ)
.dt.tz_localize(None))
.sort_values("ordered_at"))
by_send = pd.merge_asof(email_orders, sends.sort_values("sent_at"),
left_on="ordered_at", right_on="sent_at",
direction="backward", tolerance=pd.Timedelta("3D"))
print(len(email_orders), by_send["send"].notna().sum()) # 472 346
print(by_send.groupby("send", sort=False).agg(orders=("order_id", "count"),
revenue=("net_revenue", "sum")).round(0).head(3))
# orders revenue
# summer_candles 43 2669.0
# new_ceramics 44 2567.0
# weekend_edit 47 2142.0
346 of 472 email orders, 73%, came within three days after a send. The other 126 have no send in the window before them, which points to automated emails (a welcome series, an abandoned basket reminder) or to people opening an old newsletter days later. That is a useful split for Grace, and an exact join on date could never have found it, because orders rarely fall on the minute of a send. Note that the send times are in London time, so the order times are converted to London before the join. Both sides of any time join must be in the same zone.
Wide and long: what tidy data means
Joining is half of this chapter. The other half is reshaping: changing the shape of a table without changing its content.
The same July revenue can be stored two ways. Long: one row per day and channel, 186 rows, with columns date, channel and revenue. Wide: one row per day, 31 rows, and one column per channel. People read wide tables more easily, and spreadsheets are full of them. Code works better with long ones.
Hadley Wickham's paper "Tidy data" gives the long form a precise definition8. Each variable is a column, each observation is a row, and each type of observational unit is a table. In the wide table, "channel" is a variable hidden in the column headers, so filtering by channel, joining on channel or adding a seventh channel all take more work. In the long table it is a column like any other. The data storytelling chapter on tools and workflow makes the same case from the chart's side: most chart libraries expect long data.
My working rule: keep data long while you compute, and make it wide only at the end, for a person to read.
Example: the same table, both shapes
wide = daily.pivot(index="date", columns="channel", values="revenue")
print(wide.shape) # (31, 6)
print(wide.iloc[:2, :3].round(0))
# channel direct email organic_search
# date
# 2025-07-01 1242.0 964.0 2319.0
# 2025-07-02 1752.0 760.0 2804.0
long_again = wide.reset_index().melt(id_vars="date", var_name="channel",
value_name="revenue")
print(long_again.shape) # (186, 3)
186 values either way. Nothing was added or lost, only moved. That is the reshaping version of the row count contract: the number of values stays the same.
pivot and pivot_table: from long to wide
pivot turns the values of one column into column headers. It needs every combination of index and columns to be unique, because each cell can hold only one value. pivot_table does the same but sums (or averages, or counts) any cells that would collide9. Use pivot when you expect one value per cell, so that a duplicate stops you. Use pivot_table when collapsing duplicates is the point.
Example: why the spend table will not pivot
The spend table has one row per day and campaign, so there are several rows for each day and channel.
try:
spend.pivot(index="date", columns="channel", values="spend")
except ValueError as e:
print(e)
# Index contains duplicate entries, cannot reshape
spend_wide = spend.pivot_table(index="date", columns="channel",
values="spend", aggfunc="sum")
print(spend_wide.iloc[:2].round(2))
# channel paid_search paid_social
# date
# 2025-07-01 417.54 478.41
# 2025-07-02 445.66 442.78
The error is pivot doing the same job as validate: it refuses to guess. pivot_table with aggfunc="sum" sums the campaigns into channels, and the first row matches the spend table from earlier, £417.54 and £478.41. With margins=True, pivot_table also adds a total row and column, which is handy for a summary a person will read.
melt: from wide to long
melt is the reverse of pivot. You name the columns that identify a row (id_vars), and every other column is folded into two: one holding the old column name and one holding the value. It is the tool for every spreadsheet that arrives with months, weeks or channels across the top.
Example: Grace's budget plan against actual spend
Grace keeps her ad budget in a spreadsheet with one row per channel and one column per month. To compare it with the actual spend, it has to become long, with a month column to join on.
plan = pd.DataFrame({"channel": ["paid_search", "paid_social"],
"2025-07": [15000, 12000],
"2025-08": [15000, 13000],
"2025-09": [16000, 13000]})
plan_long = plan.melt(id_vars="channel", var_name="month", value_name="budget")
print(plan_long.shape) # (6, 3)
actual = (daily.assign(month=daily["date"].dt.strftime("%Y-%m"))
.groupby(["channel", "month"], as_index=False)["spend"].sum())
vs = actual.merge(plan_long, on=["channel", "month"], how="inner", validate="one_to_one")
vs["used_pct"] = (vs["spend"] / vs["budget"] * 100).round(1)
print(vs.round(1))
# channel month spend budget used_pct
# 0 paid_search 2025-07 13764.8 15000 91.8
# 1 paid_social 2025-07 13258.3 12000 110.5
Paid search used 91.8% of its July budget, paid social 110.5%, so paid social overspent by £1,258. Here an inner join is the right choice, and deliberately so: Tariq only has actuals for July, and only July can be compared. The difference from the earlier warning about inner joins is that this time the dropped rows (August and September) are dropped on purpose, and you know why.
Together with the summary above, that gives Grace a concrete answer for August: paid search returns more per pound and is under budget, paid social pays back but overspent. Moving the overspend from social to search is the obvious first step, checked against the platform numbers before anyone calls it proof.
stack, unstack and the MultiIndex
A MultiIndex is a row index with more than one level, such as date and channel together. It is what groupby with two keys produces, and what set_index(["date", "channel"]) builds. Each row is then addressed by a pair of labels. McKinney introduces it as hierarchical indexing, at the start of the same chapter2.
unstack moves the innermost row level into the columns (long to wide). stack moves the columns back into the innermost row level (wide to long). They are pivot and melt for data that lives in the index rather than in columns.
Example: one table, addressed three ways
idx = daily.set_index(["date", "channel"]).sort_index()
print(idx.loc[(pd.Timestamp("2025-07-14"), "email"), ["sessions", "orders", "revenue"]])
# sessions 360.00
# orders 18.00
# revenue 943.99
print(idx.xs("paid_social", level="channel")["spend"].head(2))
# 2025-07-01 478.41
# 2025-07-02 442.78
rev_wide = idx["revenue"].unstack("channel") # (31, 6): days by channels
rev_long = rev_wide.stack() # (186,): back to day and channel
loc with a tuple picks one row by both labels. xs takes a cross section: every row for one channel, with the channel level removed. unstack and stack move between the two shapes, and the 186 values survive both ways.
In practice I keep date and channel as ordinary columns most of the time, because merges and charts are simpler that way, and use a MultiIndex for a moment when slicing or unstacking is easier with it. It is a tool, not a home.
Where McKinney's book and pandas 2.3 differ
McKinney's third edition is from 2022, and its merge material has aged well. Its table of merge arguments already lists validate, in one line that points to the docstring for the details. This chapter gives that one line the room it deserves, because in reporting it is the argument that matters most. One detail has moved on since the book. The table says the copy argument "by default always copies". The pandas 2.3 reference notes that copy on write will make the argument ignored and that it will be removed in a future version4. You never need to pass it.
A checklist for every join
| Before the join | After the join |
|---|---|
| The grain of both tables is written down | Row count is what the grain predicts |
| Key columns have the same type on both sides (dates as dates) | Control totals equal the source totals |
| Keys are normalised: case, spaces, separators | indicator shows no unexplained left_only rows |
| Empty keys have an explicit label | Gaps are filled with zero only where zero is true |
| Timestamps are in the business time zone | Platform and shop numbers kept in separate columns |
how and validate are written out, never left to default | The assertions stay in the notebook |
My view
My view: the join is the most underrated step in marketing analytics. People argue for weeks about attribution models and budget allocation, then feed them a table in which one campaign is counted twice or a hundred orders sit on the wrong day. The model is only as right as the join underneath it.
The fix is not cleverness. It is three habits: decide the grain before writing code, build on a spine, and make every join prove itself with validate, indicator and a control total. They cost a few lines per join. In return, when Grace asks why paid search looks better this month, Tariq can show the row counts and the totals and move on to the interesting part of the conversation.
The same habits sit behind every analytics dashboard I build for clients as part of my Data Science work: the checks stay in the code, and the client owns the code, the accounts and the data.
Conclusion
Combining data from several sources comes down to a small set of tools: concat to stack tables of the same kind, merge to put different facts side by side, merge_asof for events that happen at different times, and pivot, pivot_table, melt, stack and unstack to change shape without changing content. The tools are easy. The discipline around them is what makes the numbers right.
Decide the grain, map every source to it, build on a spine, and check rows and totals at every step. With that, Fernhill's July is clear: paid search returned 4.10 and £15,582 of margin after ads, paid social returned 2.47 and £3,798, and paid social overspent its budget by 10.5%. The next chapter takes this daily table and answers more questions from it with group by and pivot tables.
