…
…
Statistics and Data Analysis Fundamentals · Lesson 10 / 44 · Grouping and merging
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
A week ago the manager asked, "Sales dropped. Why?" You turned that question into smaller questions with a clear metric, period, comparison, and breakdown. Now the manager is at your door again: "What did you find out?" In this lesson you will use every tool from the unit, one after another, to write a first answer with numbers and an honest limit.
This is a practice lesson: you will not learn a new tool. You will run an analysis from start to finish with what you learned in lessons 4–9. By the end of the lesson you will know enough to send the manager this paragraph:
Every number in this paragraph is the result of an operation you learned in this unit. The lesson has three parts. First you write a short analysis plan. Then you build the tables in five steps. Last, you turn the tables into a finding paragraph. The explanation sets up the frame and shows the result of each step; you will do the steps yourself in the exercises. The exercises move one question forward: each starts where the one before it stopped.
In this lesson you will:
You now have the whole toolbox of the unit. You read a table with read_csv (lesson 4), filter rows with a condition (5), derive a period column from the date (6), summarize groups with groupby (7), count the overlap of two variables with crosstab (8), and bring a column from another table with merge (9). Each tool gives one answer. An analysis chains them in a certain order.
Which order? The questions decide it, not the tools. In lesson 1 you wrote down the possible explanations that came to your mind and the manager's as hypotheses: something may have changed on mobile, the ad campaign may have ended, prices may have gone up in one category, customers may be spending less. Each hypothesis tells you which trace it should leave in the data. If "something changed on mobile" is true, the drop should be sharper on mobile than on desktop. If "the ads ended" is true, ad spend should really have fallen, and the orders of customers who came through ads should have dropped more. If you match the table that shows the trace with the operation that builds the table in advance, you will not get lost while writing code.
Match each hypothesis with the table you would look at to test it and the operation that builds it.
For each row, pick its match from the list, then check.
The most common trap for an analyst who opens a table for the first time is this: try every breakdown that comes to mind, produce dozens of outputs, and in the end not know which one answers the question. An analysis plan prevents this. It is a short list you write before you start coding, with four lines: which metric and how it is defined; what it is compared with; which breakdowns and why; which table for each hypothesis.
For Bazaar the plan looks like this:
| Plan line | In Bazaar |
|---|---|
| Main metric | Completed orders per month |
| Metric definition | A sale = an order whose status column is "completed"; returns and cancellations do not count |
| Supporting metrics | Monthly revenue, average basket (amount per order), return rate |
| Comparison | January–April monthly average vs. May–June monthly average |
| Breakdowns | Device, category, acquisition channel (from the hypotheses); ad spend and product price (from separate tables) |
Every line of the plan has a reason. The metric definition changes the result: an order that is returned or canceled earns the store no money, so it is not a "sale". This definition goes at the very top of the report. If you do not write it, another analyst counts all orders and the two of you report two different numbers. The main metric is the question itself ("sales dropped"); the supporting metrics help you understand why the main metric changed. The comparison must be fair: the before period is four months, the after period is two. If you compare totals, you compare two months with four months and the drop looks much bigger than it is; this is the trap of periods with different lengths from lesson 1. That is why you take the monthly average of each period. Breakdowns are chosen from the hypotheses; instead of trying every column in the data, you know in advance which question each breakdown answers.
The first step is the main and supporting metrics. You filter the completed orders, derive the period, and calculate orders, revenue, and average basket for each period. Orders and revenue are period totals, so you divide them by the number of months; the average basket is already an average per order, so you do not divide it.
One small detail: groupby("period") sorts groups alphabetically, and "after" comes before "before". So you put the table in the order you want with loc[["before", "after"]]; then dividing every column by the list [4, 2] divides the first row by 4 and the second by 2.
Example 1 (case): Main and supporting metrics
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" completed = df[df["status"] == "completed"] summary = completed.groupby("period").agg(orders=("order_id", "count"), revenue=("amount", "sum"), basket=("amount", "mean")) summary = summary.loc[["before", "after"]] summary["orders"] = summary["orders"] / [4, 2] summary["revenue"] = summary["revenue"] / [4, 2] print(summary.round(1)) print(((summary.loc["after"] / summary.loc["before"] - 1) * 100).round(1))
Output orders revenue basket
period
before 148.0 11400.5 77.0
after 97.5 6912.1 70.9
orders -34.1
revenue -39.4
basket -8.0
dtype: float64The last rows give the percent change of each metric: after / before - 1, multiplied by a hundred. Completed orders per month fell from 148 to 97.5, which is 34.1%; revenue fell 39.4%; the average basket got only 8% smaller.
See for yourself how much the metric definition changes the result. The code below uses the monthly order lists from lesson 1: one for all orders, one for completed orders only.
Change the definition: with which definition does the drop look bigger?
Pick a value; predict the output first, then look.
1definition = "all"2all_orders = [154, 177, 176, 162, 112, 104]3completed = [137, 155, 155, 145, 98, 97]4x = all_orders if definition == "all" else completed5before = sum(x[:4]) / 46after = sum(x[4:]) / 27print(definition, before, "→", after, "| %", round((after / before - 1) * 100, 1))
all 167.25 → 108.0 | % -35.4
Faded lines didn't run with this value. The difference is small (35.4 vs. 34.1) but not zero. If you do not write which definition you used at the top of the report, two analysts say two different numbers from the same data, and the meeting is spent arguing about which number is right. The definition is not a detail; it is part of the result.
Now see why supporting metrics are useful. Revenue is the product of two things: number of orders × average basket. If revenue fell, either fewer orders came, or each order is smaller, or both. The output of Example 1 tells you which one it is.
Monthly revenue fell 39%, monthly orders fell 34%, and the average basket fell 8%. What is the main source of the drop?
You know the drop comes from the number of orders. The next question is "where?". The first two breakdowns you chose from the hypotheses are device and category. For each one you count the completed orders per period with crosstab, put the columns in order with [["before", "after"]], and divide by [4, 2] to get monthly averages. You also add a change column, because in every breakdown there is a drop, and the question is not "did it drop?" but "where did it drop more sharply?".
Example 2 (case): Device and category breakdown
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" completed = df[df["status"] == "completed"] for column in ["device", "category"]: t = pd.crosstab(completed[column], completed["period"])[["before", "after"]] / [4, 2] t["change"] = (t["after"] / t["before"] - 1) * 100 print(t.round(1))
Outputperiod before after change
device
desktop 58.5 48.5 -17.1
mobile 89.5 49.0 -45.3
period before after change
category
Beauty 23.8 14.5 -38.9
Books 19.8 14.5 -26.6
Clothing 41.2 24.0 -41.8
Electronics 28.0 18.0 -35.7
Home & Living 35.2 26.5 -24.8The device table is very clear: on mobile, completed orders per month almost halved (45.3%), while on desktop the drop is 17.1%. The category table is more scattered: every category fell, the sharpest drop is in Clothing (41.8%), and the mildest is in Home & Living (24.8%). There is something to watch here: the breakdowns overlap. Most Clothing orders came from mobile (the row ratio was 0.805 in lesson 8). The sharp drop in Clothing may not be a problem of the category itself; it may be the reflection of the mobile drop in the category table.
You can read the sharpest group from the table by eye, but you can also find it with code. t["change"].idxmin() gives the row label of the smallest value in the column ("Clothing"); idxmax() gives the largest. This small method lets the code compute the result instead of you typing it, so when the table changes, the answer changes too.
Opening two breakdowns at once is the way to see the overlap. The cell below puts device and category together in the rows.
Try it now· not graded; doesn't affect progress
Run it and look at two rows: mobile Electronics 10.2 → 2.5, desktop Electronics 17.8 → 15.5. The Electronics price rose by the same amount on both devices, but the drop is almost entirely on mobile. Which two hypotheses do these two rows bring to mind together? Then add the line t["change"] = (t["after"] / t["before"] - 1) * 100 and calculate the percent change yourself.
There are two more hypotheses in the plan: ads and price. To test the ad hypothesis you look at two tables. The first is how customers found the store. This information is not in orders.csv; it is in the acquisition_channel column of customers.csv. As in lesson 9, you bring each order's customer channel with merge and check the row count after the merge: 787 completed orders went in, so 787 must come out. The second is the ad spend itself: marketing.csv keeps the ad spend and visitor count for every day. Here the periods also have different lengths (120 days and 61 days), so you compare the daily average, not the total.
Example 3 (case): Channel breakdown and ad spend
import pandas as pd df = pd.read_csv("orders.csv") df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" customers = pd.read_csv("customers.csv") completed = df[df["status"] == "completed"] merged = completed.merge(customers[["customer_id", "acquisition_channel"]], on="customer_id", how="left", validate="many_to_one") print(len(completed), len(merged)) t = pd.crosstab(merged["acquisition_channel"], merged["period"])[["before", "after"]] / [4, 2] t["change"] = (t["after"] / t["before"] - 1) * 100 print(t.round(1)) m = pd.read_csv("marketing.csv") m["period"] = "before" m.loc[m["date"] >= "2026-05-01", "period"] = "after" daily = m.groupby("period")[["ad_spend", "visitors"]].mean() print(daily.loc[[, ]].(0))
Output787 787
period before after change
acquisition_channel
ads 70.2 35.0 -50.2
organic 39.5 36.5 -7.6
referral 13.2 9.0 -32.1
social media 25.0 17.0 -32.0
ad_spend visitors
period
before 224.0 1553.0
after 25.0 1264.0The monthly orders of customers who came through ads were cut in half (50.2%); among organic customers the drop is only 7.6%. In the same period the daily ad spend fell from $224 to $25 and the daily visitors from 1,553 to 1,264. The ad campaign really did end. The date stayed as text in this example; as you saw in lesson 6, comparing year-month-day text works the same as calendar order.
The last hypothesis is price. You average the unit price of Electronics products per product and period; unstack() spreads the periods into columns.
Example 4 (case): Electronics prices before and after
import pandas as pd df = pd.read_csv("orders.csv") df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" electronics = df[df["category"] == "Electronics"] prices = electronics.groupby(["product_id", "period"])["unit_price"].mean().unstack() print(prices[["before", "after"]]) print(((prices["after"] / prices["before"] - 1) * 100).round(1).tolist())
Outputperiod before after
product_id
U01 74.95 83.95
U02 199.95 223.95
U03 64.95 72.75
U04 44.95 50.35
U05 37.45 41.95
U06 19.95 22.35
U07 54.95 61.55
U08 449.95 NaN
[12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, nan]Every Electronics product was sold 12% more expensive after May 1. U08 (the most expensive product) was not sold at all after May, so its "after" cell is empty (NaN). An empty cell does not mean "the price is zero"; it means "there are no rows to calculate from".
Now you have three traces: the mobile drop, the end of the ad campaign, and the Electronics price rise. All three start on the same date, May 1. This is where the rule from lesson 3 applies: the orders table is observational data, and it cannot separate changes that happen at the same time. Many mobile customers may have come through ads; when the ads ended, mobile orders dropped too. Or the new mobile checkout page may be losing customers, and the effect of the ads may be small. The tables fit both. The analyst's honest sentence is "these changes coincide with the drop", not "the cause of the drop is this".
Put the lines of the code that builds the channel table in the right order. df and customers are already read, and the period column is ready.
Put the code that builds the monthly completed-orders table by channel in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The manager has seen the tables and wants a short answer right away. What is your first sentence?
The manager asks you for the first sentence of the paragraph: "In one sentence, why did it drop?"
Pick an option and see what happens. There are no points; you can try the other options too.
The tables are ready; now you need to turn them into a few sentences the manager will read. There are two traps here. The first is to walk through all the tables in order: "I looked at the device table and saw this; I looked at the category table and saw that..." The reader has to search for the result. The second is to write a comfortable story that ties the differences in the tables to one cause: "Orders dropped because the ads were cut." It is easy to read, but the data does not show it.
A finding paragraph is a short text that passes between these two traps: the result comes first, every claim has a number and a unit, the breakdown says where the drop is, what the data does not say is written openly, and a next step is suggested. Four to five sentences are enough. Every sentence has a job:
| Sentence | Job | Example in Bazaar |
|---|---|---|
| 1 | Result and size (metric, period, point of comparison) | Monthly completed orders fell 34% compared with the January–April average (148 → 97.5) |
| 2 | Component: orders or basket? | The average basket fell only 8%; the main source is fewer orders |
| 3 | Where: breakdowns | 45% on mobile, 17% on desktop; 50% in the ad channel, 8% in organic |
| 4 | What changed at the same time | Daily ad spend $224 → $25; Electronics price rose 12% |
| 5 | What it does not say, and the next step | The tables cannot separate the changes; A/B experiment and a test for chance |
Every claim needs a point of comparison. "Fell 34%" alone is incomplete: compared with what? When you add "compared with the January–April average", the number gets meaning. The same goes for units: not "from 224 to 25" but "daily ad spend from $224 to $25". Two breakdowns are enough in the third sentence; if you write five, the reader misses the most important one. In the fourth sentence the words "in the same period" are chosen on purpose: they say two events happened together, not that one caused the other.
Which of the three candidate paragraphs is a good finding paragraph? (1) "Sales dropped a lot. Mobile is bad. Ads were cut. Electronics got expensive." (2) "In May–June the monthly completed orders fell 34% compared with January–April; the average basket fell only 8%. The drop is sharper on mobile (45%) and among customers who came through ads (50%). In the same period daily ad spend fell from $224 to $25 and the Electronics price rose 12%. These tables cannot separate which change had how much effect; the next step is the A/B experiment." (3) "Orders fell 34% because the ads were cut and the mobile checkout page is bad; the Electronics price rise also drove customers away."
The sentences of the paragraph came in mixed up. Put them in order by their jobs.
Put the sentences of the finding paragraph in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The flow plan → tables → paragraph is not specific to Bazaar. Think of a campus café. The manager asks, "The register took fewer receipts in November. What happened?" Two things changed in November at once: the café launched a new mobile ordering app (you order, then come and pick up), and exam season started the same month. The café has, for each half of every month, the number of receipts and the revenue for each channel (dine-in and pickup): a small table with 12 rows.
The plan is built with the same logic. The main metric is monthly receipts; the supporting metric is the average receipt amount (revenue / receipts). The comparison is the September–October average against November. The breakdown is channel, because both hypotheses leave a trace in the channel: the app should increase pickup, and exam season should shorten the time students sit in the café.
Example 5 (outside the case): Campus café
import pandas as pd cafe = pd.DataFrame({ "month": [9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11], "channel": ["dine-in", "dine-in", "pickup", "pickup"] * 3, "receipts": [620, 600, 180, 170, 640, 610, 190, 175, 430, 410, 260, 280], "revenue": [2945, 2850, 630, 595, 3040, 2897.5, 665, 612.5, 2042.5, 1947.5, 884, 952], }) monthly = cafe.groupby("month")[["receipts", "revenue"]].sum() monthly["avg_receipt"] = monthly["revenue"] / monthly["receipts"] print(monthly.round(2)) t = cafe.pivot_table(index="channel", columns="month", values="receipts", aggfunc="sum") t["before"] = (t[9] + t[10]) / 2 t["change"] = (t[11] / t["before"] - 1) * 100 print(t.round(1))
Output receipts revenue avg_receipt
month
9 1570 7020.0 4.47
10 1615 7215.0 4.47
11 1380 5826.0 4.22
month 9 10 11 before change
channel
dine-in 1220 1250 840 1235.0 -32.0
pickup 350 365 540 357.5 51.0Monthly receipts fell from the September–October average of 1,592.5 to 1,380 in November (13.3%). But the channels moved in opposite directions: dine-in fell 32% and pickup rose 51%. The average receipt amount also went from $4.47 to $4.22, because pickup receipts are smaller and their share grew. The honest finding sentence would be: "In November receipts fell 13%; dine-in dropped 32% while pickup rose 51%. This change falls in the same month as the launch of the mobile app and the start of exam season; this table cannot separate the effect of the two." Did the app move customers from the tables to pickup, or did exam season empty the tables? Looking at next year's exam season, or opening the app only on some days, could have separated this question.
Try it now· not graded; doesn't affect progress
The cell has no channel breakdown; add it yourself and print the finding as one sentence with print. Then calculate the average receipt amount for each channel too: build a second pivot table with values="revenue" and divide it by the receipts table. You should see that a dine-in receipt is about $4.75 and a pickup receipt is around $3.50.
What you did in this lesson is a large part of a data analyst's work: turning a question into a plan, running the plan with tables, and putting the tables into a paragraph. Every operation you used was simple on its own; the value is in chaining them in the right order and tying them to the right question. In Unit 1 you learned to build the question and to see the limit of observational data; with the tools of Unit 2 you gave a first answer to that question.
Your answer is not complete, and it does not have to be. You answered "how much, where, when"; you left "which one, how much effect" open and suggested how to answer it. This is exactly what a good first finding should do.
One of the supporting metrics in the plan was the return rate. Do returns explain the drop? The mean of the condition status == "returned" per period gives the share of returns.
import pandas as pd df = pd.read_csv("orders.csv") df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" df["is_returned"] = df["status"] == "returned" rate = df.groupby("period")["is_returned"].mean().loc[["before", "after"]] print((rate * 100).round(1))
Outputperiod
before 7.3
after 6.9
Name: is_returned, dtype: float64The return rate has hardly changed (7.3% → 6.9%). Returns are not the explanation of the drop; you can say this in the finding with a side sentence.
If you compare the totals of periods with different lengths, the drop looks bigger than it is.
import pandas as pd df = pd.read_csv("orders.csv") df["period"] = "before" df.loc[df[] >= , ] = completed = df[df[] == ] counts = completed[].value_counts() (, ((counts[] / counts[] - 1) * 100, 1)) (, ((counts[] / 2 / (counts[] / 4) - 1) * 100, 1))
Comparing the totals of periods with different lengths. The before period is four months (120 days), the after period is two months (61 days). If you compare totals with groupby("period")["ad_spend"].sum(), ad spend looks like it fell 94.4%; with the daily average (mean()), the real drop is 89.1%. For the number of orders, the same mistake turns a 34% drop into 67%. The right way: divide counts and totals by the number of months (or days), or take the average of the daily records directly; and in the report write "monthly average" or "daily average".
period → groupby/crosstab → [["before", "after"]] / [4, 2] → change column; if you need information from another table, merge and a row-count check.Next lesson: We said the average basket is $70.9, but are most baskets around that value? To see the distribution behind a single number, we move on to the histogram.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputWith totals: -67.1
With monthly averages: -34.1The 67% drop calculated with totals compares two months with four months; the real drop is 34% with monthly averages.