…
…
Statistics and Data Analysis Fundamentals · Lesson 7 / 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.
At Bazaar, you know that the monthly order count fell in May, and that each order's month, period, and discount now live in the table as columns. The manager's next question is: "Where is the drop?" In this lesson you will group the orders by month, device, category, and carrier, and summarize each group in one row. These are your first breakdown tables.
At the end of the lesson you will produce a table like the one below and write one sentence under it:
Output orders revenue returned_rate
category
Clothing 266 18229.52 0.169
Beauty 138 3848.56 0.036
...
Sentence: "In Clothing, the return rate is 16.9%; in every other category it is under 4% (266 orders, the category with the most orders)."In this lesson you will:
groupby to calculate counts, sums, means, and rates by group.Most analysis questions start with "for each": revenue for each device, return rate for each category, order count for each month, average delivery time for each carrier. In lesson 5 you could answer a question like this with filtering: first filter the mobile orders and add them up, then filter the desktop orders and add them up. With two groups, this works. But Bazaar has five categories, three carriers, and six months. Writing a separate line for each one takes a long time, and it raises the risk of forgetting a group or mistyping a name. Below, two filter lines and the single line that does the same job sit side by side:
import pandas as pd df = pd.read_csv("orders.csv") print(df.loc[df["device"] == "mobile", "amount"].sum().round(1)) print(df.loc[df["device"] == "desktop", "amount"].sum().round(1)) print(df.groupby("device")["amount"].sum().round(1))
Output35515.0
31328.6
device
desktop 31328.6
mobile 35515.0
Name: amount, dtype: float64The last line finds all the devices by itself, calculates a total for each one, and returns the results as one Series with the group names. To keep the examples in this lesson short, we add up the amount of all orders (returned and canceled ones included) and call it revenue. In a real report, remember to write down which definition you chose.
groupby works in three steps. First it splits the table into pieces by the values of the key column. Then it applies the same summary to each piece. At the end it combines the results in one table with the group names. When you read the pattern, ask three questions in order: by what (device), which column (amount), and how do I summarize (sum)? In short: df.groupby(key)[column].summary().
Let's see this on a small table you can check by hand. There are five sales from two branches of a stationery chain:
import pandas as pd t = pd.DataFrame({ "branch": ["A", "B", "A", "B", "A"], "amount": [100, 250, 300, 50, 200], }) print(t.groupby("branch")["amount"].agg(["count", "sum", "mean"]))
Output count sum mean
branch
A 3 600 200.0
B 2 300 150.0Branch A has three sales (100 + 300 + 200 = 600, mean 200). Branch B has two sales (250 + 50 = 300, mean 150). Your pencil result and the pandas result are the same. The group names moved into the index of the result. That is why the table shows the branch heading on the left, with the rows A and B.
In the branch example, what does t.groupby("branch")["amount"].sum() do behind the scenes? Put the steps in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The common summaries are: sum (total), mean (average), count (number of non-missing values), size (number of rows), min and max (smallest and largest), and nunique (number of distinct values, for example how many different customers in each category). Two of these are often confused: size and count. size() counts all the rows in the group and is written without choosing a column. count() counts the non-missing values in the column you chose. If the column has no missing values, both give the same result; if it has some, they differ.
delivery_days is empty for canceled orders. What does df.groupby("carrier")["delivery_days"].count() count?
import pandas as pd df = pd.read_csv("orders.csv") print(df.groupby("carrier").size()) print(df.groupby("carrier")["delivery_days"].count())
Outputcarrier
Arrow Express 350
Caravan Freight 238
Gull Post 297
dtype: int64
carrier
Arrow Express 340
Caravan Freight 226
Gull Post 285
Name: delivery_days, dtype: int64The difference (10 + 12 + 12 = 34) is exactly the number of canceled orders. Saying "Caravan Freight carried 226 orders" would be wrong: 226 is the number of orders that have a recorded delivery day.
Change the summary function below and see what the same grouping can produce:
Change the summary function: which numbers does the same grouping give for branches A and B?
Pick a value; predict the output first, then look.
1import pandas as pd2summary = "count"3t = pd.DataFrame({4 "branch": ["A", "B", "A", "B", "A"],5 "amount": [100, 250, 300, 50, 200],6})7print(t.groupby("branch")["amount"].agg(summary).tolist())
[3, 2]
Faded lines didn't run with this value. The groups stay the same (A and B); only the summary applied to each piece changes. count gives the number of sales, sum the total, mean the average, and max the largest sale. agg can also take the summary name as a string.
Often one number per group is not enough: how many orders are there, what is the average, what is the total? When agg gets a list, it calculates each summary as a separate column:
import pandas as pd df = pd.read_csv("orders.csv") print(df.groupby("device")["amount"].agg(["count", "mean", "sum"]).round(1))
Output count mean sum
device
desktop 369 84.9 31328.6
mobile 516 68.8 35515.0The list form is ideal for a quick look, but the column names are function names, and all the columns come from the same column. In a report table, you want meaningful column names, and you want to summarize different columns. For this you write a named aggregation: each argument has the form new_name=(column, function). Because you choose the column names, the table explains itself, like the headings in a report.
import pandas as pd df = pd.read_csv("orders.csv") summary = df.groupby("category").agg( orders=("order_id", "count"), revenue=("amount", "sum"), avg=("amount", "mean"), ) print(summary.round(0).sort_values("revenue", ascending=False))
Output orders revenue avg
category
Electronics 156 22850.0 146.0
Home & Living 208 19364.0 93.0
Clothing 266 18230.0 69.0
Beauty 138 3849.0 28.0
Books 117 2551.0 22.0The result is a DataFrame, so you can sort it by any column with sort_values from lesson 5. When you read the table, look at two columns together: Electronics brings in the most revenue, but Clothing is ahead in the number of orders. In Electronics, the average amount per order is about $146, and in Clothing it is $69. Try it yourself:
Try it now· not graded; doesn't affect progress
After grouping, the group names move into the index. If you only want to read the table, this is not a problem. But if you will join the result with another table or pass it to a chart, it is easier when the group names are a normal column. There are two ways: add reset_index() to the result, or write groupby("device", as_index=False) from the start.
import pandas as pd df = pd.read_csv("orders.csv") summary = df.groupby("device", as_index=False).agg(orders=("order_id", "count")) print(summary)
Output device orders
0 desktop 369
1 mobile 516Counts and totals grow with the size of the groups, so for comparison a rate is often more meaningful. In lesson 5 you saw that the mean of a condition gives a share: True counts as 1 and False as 0. The same idea works in grouping. First you create a True/False column that marks the returned orders, then you take the group mean of this column. The result is the return share inside each group.
import pandas as pd df = pd.read_csv("orders.csv") df["returned"] = df["status"] == "returned" summary = df.groupby("category").agg( orders=("order_id", "count"), returned_rate=("returned", "mean"), ) print(summary.round(3).sort_values("returned_rate", ascending=False))
Output orders returned_rate
category
Clothing 266 0.169
Beauty 138 0.036
Home & Living 208 0.034
Electronics 156 0.032
Books 117 0.01716.9% of Clothing orders were returned; in the other four categories the rate is under 4%. This is the first concrete clue for Bazaar. Now ask a different question: what percent of all orders are Clothing? This is the share of the group within the whole. It is found not with grouping but with value_counts from lesson 4; normalize=True turns counts into shares:
import pandas as pd df = pd.read_csv("orders.csv") print(df["category"].value_counts(normalize=True).round(3))
Outputcategory
Clothing 0.301
Home & Living 0.235
Electronics 0.176
Beauty 0.156
Books 0.132
Name: proportion, dtype: float64The two questions look alike, but they have different denominators. The denominator of "What percent of Clothing orders were returned?" is the Clothing orders (45 / 266 = 16.9%). The denominator of "What percent of orders are Clothing?" is all orders (266 / 885 = 30.1%). There is a third one: "What percent of the returns come from Clothing?" Its denominator is all returns: 45 of 64 returns, which is 70.3%. When you write a report, always state the denominator inside the sentence.
Match each question with the code that answers it.
For each row, pick its match from the list, then check.
When you report a rate or a mean, keep the group size next to it. Books seems to have the lowest return rate (1.7%), but this rate comes from only 117 orders and 2 returns; with two more returns, the rate would almost double. The mean of a group of twenty orders is much more unstable than the mean of a group of two hundred. This is why a good summary table always keeps the count column (orders): the reader can see how solid each rate is.
The same care is needed when you decide with totals. In the device summary, mobile revenue ($35,515) is larger than desktop revenue ($31,329). Does this show that mobile is more "valuable"?
import pandas as pd df = pd.read_csv("orders.csv") df["returned"] = df["status"] == "returned" print(df.groupby("device")["returned"].mean().round(3))
Outputdevice
desktop 0.062
mobile 0.079
Name: returned, dtype: float64The marketing team writes: "Mobile revenue is $35,515, desktop is $31,329. Mobile is the more valuable channel, so let's move the budget there." What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
Sometimes the answer to the question is not one row per group but a comparison of every row with its own group: "Is this order bigger than the mean of its own category?" A $75 order is small in Electronics but very large in Books; the yardstick for comparison changes with the category. transform calculates the group summary, but it writes the result back not as one value per group but as the value of its own group on every row. Because the result has the same length as the table, you can add it as a new column.
import pandas as pd df = pd.read_csv("orders.csv") df["cat_avg"] = df.groupby("category")["amount"].transform("mean") print(df[["category", "amount", "cat_avg"]].head(3).round(1)) print(round((df["amount"] > df["cat_avg"]).mean(), 3))
Output category amount cat_avg
0 Home & Living 249.9 93.1
1 Electronics 75.0 146.5
2 Home & Living 165.0 93.1
0.353The first order ($249.90) is far above the Home & Living average ($93.1); the second order ($75.00) is below the Electronics average ($146.5). The last line says that 35.3% of the orders are larger than the mean of their own category. It is not surprising that this is less than half: in every category, a few very large orders pull the mean up. You will see the reason in the distribution lessons; in lesson 16 we will take the comparison inside a category further with the same transform pattern.
In a table with 885 rows, how many rows do df.groupby("category")["amount"].mean() and df.groupby("category")["amount"].transform("mean") return?
Grouping is not specific to store data. Think of the repair records of a university dorm: each record has the block where the fault happened, the type of fault, and how many days it took to fix. The dorm manager asks, "In which block are faults fixed more slowly?" The question again starts with "for each block":
import pandas as pd dorm = pd.DataFrame({ "block": ["A", "A", "A", "A", "B", "B", "B", "B", "C", "C"], "type": ["electrical", "water", "internet", "internet", "water", "internet", "electrical", "water", "internet", "water"], "days": [1, 2, 3, 2, 1, 2, 1, 2, 6, 4], }) summary = dorm.groupby("block").agg(faults=("type", "count"), avg_days=("days", "mean")) print(summary)
Output faults avg_days
block
A 4 2.0
B 4 1.5
C 2 5.0Block C has by far the highest mean (5 days). But the faults column gives a warning: this mean comes from only two records. One long fault can pull C's mean up by itself. Before saying "the maintenance team is slow in block C," you need to wait for more records or look at the details of the two faults. This care was possible because the count column stayed in the table.
Try it now· not graded; doesn't affect progress
If we reduce the whole lesson to one sentence: when you see a question that starts with "for each ...", choose the key (by what), the column (what), and the summary (how); sort the result and name the standout group together with its size.
You can now produce the monthly lists from lesson 1 with a single grouping. The month column is derived from the date, as in lesson 6.
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) df["month"] = df["date"].dt.month monthly = df.groupby("month").agg(orders=("order_id", "count"), revenue=("amount", "sum"), avg_order=("amount", "mean")) print(monthly.round(1))
Output orders revenue avg_order
month
1 154 11395.3 74.0
2 177 15674.2 88.6
3 176 13257.4 75.3
4 162 11809.0 72.9
5 112 8663.6 77.4
6 104 6044.1 58.1The orders, revenue, and average order lists we wrote by hand in lesson 1 are the three columns of this table. The drop starts in May; to see on which device it is sharper, you need month and device together.
The target table from the start of the lesson: order count, revenue, and return rate side by side.
import pandas as pd df = pd.read_csv("orders.csv") df["returned"] = df["status"] == "returned" summary = df.groupby().agg( orders=(, ), revenue=(, ), returned_rate=(, ), ) (summary.(3).sort_values(, ascending=))
Applying mean to the whole table without choosing the column to summarize:
Outputdf.groupby("device").mean()The table has text columns such as order_id, category, and status. The mean of text cannot be taken, so you get a TypeError runtime error. Grouping does not summarize every column in a meaningful way by itself. The correct way is to write clearly which column you are summarizing: df.groupby("device")["amount"].mean(), or a named aggregation for several columns.
df.groupby(key)[column].summary() splits the table into groups, applies the summary to each group, and combines the results; size() counts rows, and count() counts non-missing values.agg with a list produces several summaries, and the form new_name=(column, function) produces named report columns; the group mean of a True/False column gives the share within the group, and value_counts(normalize=True) gives the share within the whole.transform writes the group summary onto every row, so you can compare a row with its own group.Next lesson: We worked with a single breakdown; the question "Did mobile drop in May?" needs two breakdowns: month and device together. Pivot and cross tables come next.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output orders revenue returned_rate
category
Clothing 266 18229.52 0.169
Beauty 138 3848.56 0.036
Home & Living 208 19364.13 0.034
Electronics 156 22850.34 0.032
Books 117 2551.02 0.017Sentence: "In Clothing, the return rate is 16.9%; in every other category it is under 4% (266 orders, the category with the most orders)." The sentence carries the rate, the comparison, and the group size together; it does not claim anything about the reason for the returns.