…
…
Statistics and Data Analysis Fundamentals · Lesson 9 / 44 · Grouping and merging
PreviewIn this lesson you will
merge, add cost or customer information to the orders table, and calculate a new measure such as profit or acquisition channelYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The manager asked two new questions: "Did profit drop too?" and "What happened to the orders of customers who came through ads?" The answers to both are missing from orders.csv, because the cost of a product is in products.csv, and the channel a customer came from is in customers.csv. In this lesson you will join the tables on their shared keys and answer both questions.
At the end of the lesson you will be able to combine three files and print these three lines:
Output885 885
Gross profit of completed orders: $21,754
Monthly orders of customers who came through ads: 79.5 → 39.0The first line looks ordinary, but it holds the most important habit of this lesson: before the join and after the join there are 885 rows. You will see why this matters in section 5.
In this lesson you will:
inner, left, right, outer) keep.Real data almost never comes in one table. Bazaar's system has three separate tables, and each piece of information is stored in only one place. The cost of a product is written once in the products table; if that product was sold 15 times, the cost is not repeated 15 times. The city of a customer is also stored once, in the customers table. This has two benefits: the tables stay small, and when a fact changes (for example, the cost of a product), it is corrected in one place. The price is this: to answer a question, you need to bring the tables together again.
The columns that connect tables are key columns. In lesson 2 you saw that the column with a single value in every row names the unit of observation: order_id is unique in every order, product_id is unique in every row of the products table, and customer_id is unique in every row of the customers table. The orders table also has product_id and customer_id, but there they are not unique: the same product appears in many orders. These columns are the bridge that links an order to the right row in the products table and the customers table.
In the diagram, each line says "many" at the orders end and "one" at the other end: many orders point to the same product, and many orders point to the same customer. Knowing which table holds which piece of information is the first step of a join. Which information is where?
Match each piece of information with the table that stores it.
For each row, pick its match from the list, then check.
mergemerge matches two tables on a shared key column. The pattern is: left.merge(right, on="key", how="left"). For every row of the left table, pandas looks in the right table for the row with the same key value and adds its columns next to it. on is the key column that has the same name in both tables; if the names differ, you write left_on="..." and right_on="..." (Example 9). If you have taken the SQL course, this is the pandas version of a JOIN; if you have not, you do not need that knowledge.
First, a small example you can check by hand. A school keeps its student list (s) and its score records (r) separately. The score table has only the student number; we want to bring the student's name next to every score. Note: student 105 has no record in the list (maybe a guest student from another school), and Cem (103) has no scores at all.
Example 1 (outside the case): The student name next to the scores
import pandas as pd s = pd.DataFrame({"student_id": [101, 102, 103, 104], "name": ["Ada", "Bora", "Cem", "Deniz"]}) r = pd.DataFrame({ "student_id": [101, 101, 102, 104, 105], "subject": ["Math", "Phys", "Math", "Math", "Math"], "score": [80, 70, 65, 90, 55], }) b = r.merge(s, on="student_id", how="left") print(b) print(len(r), len(b))
Output student_id subject score name
0 101 Math 80 Ada
1 101 Phys 70 Ada
2 102 Math 65 Bora
3 104 Math 90 Deniz
4 105 Math 55 NaN
5 5Read it line by line. Ada has two scores, so her name was written on two rows; this multiplication is correct, because the unit of observation of this table is the score record, not the student. Student 105 has no match in the student list: because how="left" keeps all rows of the left table (the score table), that row stayed and its name became NaN. Cem is not in the result at all, because the main table is the score table and Cem has no score. The result has 5 rows: the same as the score table.
If you do not write how, pandas uses inner by default: it keeps only the rows that have a match in both tables. How many rows does inner return with the same two tables?
With the tables of Example 1, how many rows does r.merge(s, on="student_id") return (no how, so inner)?
Now try it yourself: (1) Change how to "inner", "left", and "outer"; see that the row counts are 4, 5, and 6, and that with outer Cem's score value comes as NaN. (2) Swap the tables: s.merge(r, on="student_id", how="left"). Now the main table is the student list; Cem comes with one row, and 105 is dropped.
Try it now· not graded; doesn't affect progress
Back to the profit question. The gross profit of an order is the amount the customer paid minus the cost of the products to the store: profit = amount − cost × quantity. Amount and quantity are in the orders table; cost is in the products table. The orders table goes on the left (each row is an order, and we do not want to lose any), and the products table goes on the right.
Take only the needed columns from the right table: u[["product_id", "cost"]]. There is a reason for this. If the two tables have a column with the same name besides the key, pandas keeps both and adds a suffix to their names to tell them apart: because category is in both the orders table and the products table, the result has category_x (from the left) and category_y (from the right). One does not overwrite the other, but a column called df["category"] no longer exists, and the code that follows gives an error. If you take only the key and the cost, this problem never starts.
Example 2 (case): The profit of every order
import pandas as pd df = pd.read_csv("orders.csv") u = pd.read_csv("products.csv") d = df.merge(u[["product_id", "cost"]], on="product_id", how="left", validate="many_to_one") d["profit"] = d["amount"] - d["cost"] * d["quantity"] print(len(df), len(d)) print(d[["product_id", "quantity", "amount", "cost", "profit"]].head(3)) print(d.groupby("category")["profit"].sum().round(0).sort_values(ascending=False))
Output885 885
product_id quantity amount cost profit
0 U09 2 249.90 76.45 97.00
1 U01 1 74.95 54.10 20.85
2 U16 1 164.95 97.05 67.90
category
Clothing 9302.0
Home & Living 7555.0
Electronics 5403.0
Beauty 2049.0
Books 734.0
Name: profit, dtype: float64Check the first row by hand: 2 items, $249.90 paid, the product costs $76.45; profit is 249.90 − 2 × 76.45 = $97.00. We will explain the validate="many_to_one" argument in section 5; for now, know that it makes pandas check the promise "many rows on the left, one row on the right."
There is a problem with this table. The column that came from the join was written on every row, but it is not meaningful for every row. In a canceled order, no money changed hands; in a returned order, the product came back. These orders have no "profit." The category totals above used all orders to show the join; in a real profit report, you first filter to completed orders only, as in lesson 5.
Example 3 (case): Profit of completed orders and category margin
import pandas as pd df = pd.read_csv("orders.csv") u = pd.read_csv("products.csv") d = df.merge(u[["product_id", "cost"]], on="product_id", how="left", validate="many_to_one") d["profit"] = d["amount"] - d["cost"] * d["quantity"] t = d[d["status"] == "completed"] profit = round(t["profit"].sum()) revenue = round(t["amount"].sum()) print(f"Gross profit of completed orders: ${profit:,}") print("Percent of revenue:", round(profit / revenue * 100, 1)) g = d.groupby("category")[["profit", "amount"]].sum() print((g["profit"] / g["amount"] * 100).round(1))
OutputGross profit of completed orders: $21,754
Percent of revenue: 36.6
category
Beauty 53.2
Books 28.8
Clothing 51.0
Electronics 23.6
Home & Living 39.0
dtype: float64The 787 completed orders brought $59,426 in revenue and $21,754 in gross profit: about $37 of every $100 of sales is profit. The category rows show the share of profit, that is, the margin (these rows still use all orders). Electronics is large in revenue but low in margin; in Clothing and Beauty, half of the sales is profit. This is why Clothing leads in total profit.
Try it yourself: (1) Write only u instead of u[["product_id", "cost"]] and add print(d.columns.tolist()); see the category_x and category_y columns (the last line will also give an error; why?). (2) Undo it; derive a month column (d["month"] = d["date"].str[5:7]) and total the profit by month. (3) Calculate the margin with completed orders only: group t instead of d.
Try it now· not graded; doesn't affect progress
howThe how argument says what happens to the rows that do not match. There are four options. inner keeps only the rows that have a match in both tables. left keeps all rows of the left table; if there is no match on the right, the new columns become NaN. right is the opposite. outer keeps all rows from both sides. The left table is your main table: your unit of observation is there, and you are looking for the answer for its rows. Your default choice in analysis should be left, because the main table does not lose rows and missing matches show up as NaN; you can notice a problem you can see.
inner seems safe, because "only the full matches" sounds clean. But it gives no warning about the rows it drops. Let's put the customers table on the left and build a table of "the orders of every customer."
Example 4 (case): Customers who never ordered
import pandas as pd df = pd.read_csv("orders.csv") m = pd.read_csv("customers.csv") no_orders = m[~m["customer_id"].isin(df["customer_id"])] print(len(m), len(no_orders)) inner = m.merge(df[["customer_id", "order_id"]], on="customer_id") left = m.merge(df[["customer_id", "order_id"]], on="customer_id", how="left") print(len(inner), len(left), left["order_id"].isna().sum())
Output577 53
885 938 53Of the 577 customers, 53 signed up but placed no order between January and June. The inner join returned 885 rows: one row per order, and those 53 customers quietly disappeared. If a marketing team prepared a "customer list" with this table, the people who need the most attention (those who did not order) would not be on the list. The left join returned 938 rows: 885 order rows, plus one row for each of the 53 customers who did not order, with an empty order_id.
The pattern in the first line is called an anti-join: "rows that have no match in the other table." It is built with isin and ~, which you saw in lesson 5: customers whose customer number is *not* among the numbers in the orders table. You reach the same result by joining with left and selecting the rows with an empty order_id. If you write indicator=True in merge, it also adds a _merge column that shows where each row came from; you do not need it in this lesson.
Which rows does each value of the how argument keep?
For each row, pick its match from the list, then check.
innerleftrightouterYou saw it in Example 1: if a key appears in more than one row of the right table, the left row is copied that many times. That was correct for the student and score tables. But when you add product information to the orders table, the right side (the products table) must have one row for each product. What happens if someone accidentally enters the same product twice in the products table? pandas writes every order of that product twice, the revenue and cost totals grow too big, and no error message appears.
Example 5 (case): A repeated product row
import pandas as pd df = pd.read_csv("orders.csv") u = pd.read_csv("products.csv") u2 = pd.concat([u, u.head(1)]) # adds the U01 row to the table one more time print(len(u), len(u2)) b = df.merge(u2[["product_id", "cost"]], on="product_id", how="left") print(len(df), len(b)) print("U01 orders:", (df["product_id"] == "U01").sum())
Output40 41
885 900
U01 orders: 15(pd.concat is there only to create the error on purpose; we do not learn to stack tables on top of each other in this lesson.) When the products table grew to 41 rows, the join returned 900 rows: each of the 15 orders of U01 was written twice. The revenue calculated with this table would be larger than the real one.
You do not have to look for this error by eye every time. The validate="many_to_one" argument makes pandas check the relationship "many on the left, one on the right." If you do the same join with u2 and this argument, pandas stops with an error called MergeError and says that the keys in the right table are not unique. The error message looks annoying, but it is much better than silently producing a wrong number: you catch it before you take a wrong number to the manager. This is why joining is the quietest source of errors in analysis: it can lose rows or multiply them, and it makes no sound in either case.
You joined the 885-row orders table with the products table and the result has 900 rows. What is the most likely cause?
Watch how big the multiplication gets in a small table. There are three products (A, B, C) and five orders; A appears in two orders. The repeats variable says how many extra times A was entered in the products table.
Change the repeats value: what happens to the row count and the cost total?
Pick a value; predict the output first, then look.
1import pandas as pd2u = pd.DataFrame({"product": ["A", "B", "C"], "cost": [10, 20, 30]})3s = pd.DataFrame({"order": [1, 2, 3, 4, 5], "product": ["A", "A", "B", "C", "C"]})4repeats = 05# adds the A row to the products table this many more times6u2 = pd.concat([u] + [u.head(1)] * repeats)7b = s.merge(u2, on="product", how="left")8print(len(s), len(b), b["cost"].sum())
5 5 100
Faded lines didn't run with this value. A appears in two orders. Every extra copy of A in the products table writes these two orders one more time: 2 rows and 2 × 10 = $20 of extra cost. The order count (5) never changes, yet the totals grow.
There is a silent error in the opposite direction too: no row matches. Keys that look the same in two tables can be different for the computer. "U01" and "U01 " with a space at the end are two different strings; and if 101 is stored as a number in one table and as the string "101" in the other, they do not match either. In such a case pandas gives no error: with a left join the row count is correct, but every cell of the new column is NaN.
Example 6 (case): Keys with a space at the end
import pandas as pd df = pd.read_csv("orders.csv") u = pd.read_csv("products.csv") u3 = u.copy() u3["product_id"] = u3["product_id"] + " " print(u3["product_id"].head(2).tolist()) z = df.merge(u3[["product_id", "cost"]], on="product_id", how="left") print(len(z), z["cost"].isna().sum())
Output['U01 ', 'U02 ']
885 885The row count is 885: the row check alone did not catch this error. But in the cost column, 885 of 885 rows are empty. This is why the check has two parts: the row count (for multiplication and loss) and the count of empty values in the new column (for no match). The isna().sum() from lesson 4 is useful here. If the empty count is greater than zero, first look at the spelling and the type of the key in both tables; you can clean the spaces with .str.strip() from lesson 6.
Put the lines of a safe join in order.
Put the safe-join habit in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
On to the second question: what happened to the orders of customers who came through ads? The acquisition channel is in the customers table; the orders table is on the left again. After that we use the period column from lesson 6 and the cross table from lesson 8. One detail: crosstab sorts columns alphabetically, so the "after" column comes first; we fix the order with [["before", "after"]]. Finally, remember the trap from lesson 1: "before" is four months and "after" is two months. Before comparing, you need to convert to a monthly average.
Example 7 (case): Channel and period
import pandas as pd df = pd.read_csv("orders.csv") m = pd.read_csv("customers.csv") d2 = df.merge(m[["customer_id", "acquisition_channel"]], on="customer_id", how="left") print(len(d2), d2["acquisition_channel"].isna().sum()) d2["period"] = "before" d2.loc[d2["date"] >= "2026-05-01", "period"] = "after" k = pd.crosstab(d2["acquisition_channel"], d2["period"])[["before", "after"]] print(k) k["before"] = k["before"] / 4 k["after"] = k["after"] / 2 print(k) print("Monthly orders of customers who came through ads:", k.loc["ads", "before"], "→", k.loc["ads", "after"])
Output885 0
period before after
acquisition_channel
ads 318 78
organic 178 80
referral 58 18
social media 115 40
period before after
acquisition_channel
ads 79.50 39.0
organic 44.50 40.0
referral 14.50 9.0
social media 28.75 20.0
Monthly orders of customers who came through ads: 79.5 → 39.0The check is clean: 885 rows, and no order has an empty channel. Monthly orders went down in every channel, but the size of the drop is different. For organic customers it went from 44.5 to 40, about 10 percent. For customers who came through ads it went from 79.5 to 39, that is, it was cut in half. Remember lesson 3: this is observational data. The table shows where the drop is concentrated, not why. Even so, this finding will be one of the hypotheses you test in lesson 10.
You take the channel table to the manager. Monthly orders of customers who came through ads were cut in half (79.5 → 39.0), and organic shows a drop of about 10 percent. What do you say?
Pick an option and see what happens. There are no points; you can try the other options too.
Calculating the channel share with two different units of observation gives different results: the share of orders after the join, and the share of customers directly from the customers table.
import pandas as pd df = pd.read_csv("orders.csv") m = pd.read_csv("customers.csv") d = df.merge(m[["customer_id", "acquisition_channel"]], on="customer_id", how="left") print(d["acquisition_channel"].value_counts(normalize=True).round(3)) print(m["acquisition_channel"].value_counts(normalize=True).round(3))
Outputacquisition_channel
ads 0.447
organic 0.292
social media 0.175
referral 0.086
Name: proportion, dtype: float64
acquisition_channel
ads 0.399
organic 0.329
social media 0.180
referral 0.092
Name: proportion, dtype: float6439.9 percent of customers came through ads, but 44.7 percent of orders came from them. When you say "the share of customers who came through ads," you need to say whether you counted customers or orders.
In a cinema's ticket table, the film code is in the film column; in the film table, it is in the film_id column. When the names are different, you write left_on
Joining without noticing that the right key repeats. If one product_id appears twice in the products table, every order of that product is written twice; rows multiply silently, the revenue and profit totals grow too big, and no error message appears. After every join, compare the row count with len, and write validate="many_to_one" when you add information to the orders table. Stacking tables on top of each other (pd.concat) is a separate operation; this lesson has only side-by-side joins.
left.merge(right[["key", "needed_column"]], on="key", how="left") adds the columns of the matching right row to every row of the main table; taking only the needed column from the right avoids the _x, _y suffixes.inner keeps only what is on both sides and drops unmatched rows without a warning; the default choice in analysis is left. To find rows with no match, use ~isin (anti-join).validate="many_to_one" catches a repeated right key as an error.Next lesson: The tools of the unit are complete: read, filter, derive, group, cross-tabulate, join. In the next lesson you will use all of them to write the first answer to the manager's question "What changed in May?"
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.
right_ononimport pandas as pd tickets = pd.DataFrame({"film": ["F1", "F2", "F1", "F3", "F2", "F1"], "price": [9, 8, 9, 10, 8, 6]}) films = pd.DataFrame({"film_id": ["F1", "F2", "F3"], "genre": ["comedy", "drama", "comedy"]}) b = tickets.merge(films, left_on="film", right_on="film_id", how="left") print(len(tickets), len(b)) print(b.groupby("genre")["price"].agg(["count", "sum"]))
Output6 6
count sum
genre
comedy 4 34
drama 2 16Both key columns stay in the result (film and film_id); you can drop one if you like.