merge under the microscope
Archive Deck, Tier 5
The year is 2184. Vault-9, deep-storage sector. The black box from Kotomarket, an online store for cats that shut down in December 2183, is finally giving up its secrets: you know how to read a table, clean it, and describe it. But the tables say little when viewed separately.
Here is the order log: order_id, product_id, qty. How much revenue did order 501 generate? You can't tell because the log has no price. Here is the catalog—a product lookup table, meaning each row describes one product. It has price, but no customers or dates. The answer to “how much revenue did the store make?” isn't stored in either table. You need both tables to find it.
L., entry #31: One table gives you a fact. Meaning appears when the fact meets a lookup table. Everything I did at this company was stitching tables together and checking where the seams came apart.
What is a join?
A join (merge) is an operation on two tables that returns a third table. It matches rows by a key and combines data from matching rows into one wider row. By default, only matches appear in the result: if a key value has no counterpart in one of the tables, there is no matching pair to include.
What counts as a “match”? A key is one column or a set of columns whose values show which rows in the two tables refer to the same object. Here the key is obvious: product_id appears in both the log and the catalog, and in both places its values identify a specific product.
merged = orders.merge(products, on='product_id')
Read this as: “take orders, attach products, and match them on the product_id column.” In this expression, orders is the left table and products is the right table. These are roles in this operation, not permanent properties of the tables. Reverse the call, and the roles reverse too.
A key isn't just any shared column
Choose a key by meaning, not by name: its values must represent the same thing in both tables. Both tables might contain a column called id, but in one it could identify an order and in the other a product. Joining on it would make no sense, even though pandas would still perform the merge.
The next question is whether the key values are unique in the right table. In the catalog, each product_id appears exactly once: one row represents one product. In the log, the same value can appear any number of times because customers can buy the same laser again and again. This is a many-to-one relationship: many rows on the left → one row on the right.
If a key value repeats on the right, one row on the left will match every corresponding row on the right. The result can then contain more rows, and unexpected duplicates can distort your calculations. So check uniqueness with code rather than by eye:
products['product_id'].is_unique # True — the lookup table is unique
Here, True means exactly one thing: products contains no duplicate product_id values. This check tells you nothing about whether the prices or any other fields are correct.

product_id key, and columns from the lookup table are added to that row. In this example, each key matches exactly one catalog row, so four rows went in and four rows came out.Close-up: four rows under the microscope
Look at the actual rows. It's the easiest way to see exactly what merge does.
The products catalog has two rows:
| product_id | product_name | price |
|---|---|---|
| 101 | Cat Food "Purrchow" | $89 |
| 103 | Laser Toy "Red Dot" | $35 |
The orders log has four rows, and product 103 appears in THREE orders:
| order_id | product_id | qty |
|---|---|---|
| 501 | 101 | 2 |
| 502 | 103 | 1 |
| 503 | 103 | 3 |
| 504 | 103 | 2 |
Now walk through the join row by row, the way pandas does it:
- row 501 → key 101 → exactly one catalog row has key 101 → combine them → the order gets
product_name = 'Cat Food "Purrchow"'andprice = 89; - row 502 → key 103 → one catalog row has key 103 → the order gets
product_name = 'Laser Toy "Red Dot"'andprice = 35; - row 503 → key 103 → the same catalog row → the order gets the same name and the same $35 price;
- row 504 → key 103 → that same catalog row again → the order gets the same name and the same $35 price.
This is a many-to-one relationship in practice: one catalog row supplied data to THREE order rows. The $35 price was copied into each of them; the catalog itself did not change or get “used up.”
The output has 4 rows, the same number as the order log. That follows from the relationship: as long as the key in the right table is unique and every order finds a match, merge can neither drop nor duplicate an order row. It only adds columns from the catalog.
Granularity of the result
Granularity describes what one row of a table represents, or its level of detail. Before the join: “one row = one order.” After the join: still “one row = one order,” but now each row contains more information about that order. The has not changed.
This is the investigator's main question after every merge: “What does one row of the result represent now—is it still one order, or something else?” As long as the answer is “the same order,” the join has not duplicated order-level metrics. For example, you can calculate revenue as qty * price and then sum the results. But you cannot treat the sum of the price column as revenue: a product's unit price is repeated in every order row.
Later we'll see joins where the meaning of one row changes, and that changes the meaning of the numbers in the report too.
When the key has different names
In real data, matching columns often have different names: the order export calls the product pid, while the catalog calls it id. There is no shared column name, so on= won't work. Instead, specify the key separately for each side:
orders_raw.merge(catalog, left_on='pid', right_on='id')
left_on is the column from the LEFT table; right_on is the column from the RIGHT table. The values must match; the names do not have to. The result keeps BOTH columns, pid and id, because pandas doesn't know which one you consider primary and won't remove either. You can drop the extra column right after the join with .drop(columns='id').
Where _x and _y come from
There is another complication. What if both tables have a column called name, but the columns mean DIFFERENT things? In the order export, name is the customer's name (“Milo”); in the catalog, name is the product name (“Cat Food "Purrchow"”). Neither column is part of the key, but they have the same name.
When pandas joins the tables, it has to keep both columns and give them different names. It adds _x to the column from the LEFT table and _y to the column from the RIGHT table. That's how a report ends up with the mysterious name_x / name_y pair, and a week later nobody remembers which is the customer and which is the product.
You can fix that with one argument:
orders_raw.merge(catalog, left_on='pid', right_on='id',
suffixes=('_customer', '_product'))
Now the columns are called name_customer and name_product. The tuple follows the same order: first the suffix for the left table, then the suffix for the right, just like _x and _y but with meaningful names.
Narrow the lookup table before the join
A useful habit is to avoid bringing the entire lookup table into a join. Select the key and only the columns you actually need.
merged = orders.merge(products[['product_id', 'price']], on='product_id')
There are three reasons:
- Name conflicts. If a potentially conflicting column isn't included in the join, the corresponding
_xand_ycolumns won't appear. - Readability. An error can hide in a 40-column report. In a six-column report, it's much easier to spot.
- Memory. Values from every added lookup-table column are copied into the result for all matching rows. If you need only the key and price from a 30-column catalog, pass those two instead of filling the result with data you won't use.
L., entry #32: Joining the whole lookup table is like summoning the entire village for questioning. Bring in only the witnesses who matter.
Your first metric from joined data
This is why we joined the tables. The log had qty, the catalog had price, but neither table contained revenue. After the join, quantity and price are in the same row, so you can calculate revenue in one operation:
merged['revenue'] = merged['qty'] * merged['price']
This is element-wise (vectorized) multiplication, which you already know from the pandas chapter: in each row, the value of qty is multiplied by the value of price. No loops. You can then revenue like any other column:
merged['revenue'].sum() # total revenue
merged.groupby('product_name')['revenue'].sum() # revenue by product
A reliable workflow for this kind of metric is: join → calculate each row → aggregate. First, match a price to each order row. Then calculate that row's revenue, and only after that add the results together. Check each step separately.
Common mistake: multiplying totals
This is tempting, but wrong:
merged['qty'].sum() * merged['price'].sum() # ✗ meaningless
Here, the total number of units is multiplied by the sum of all prices, producing a number with no useful meaning. It is neither an average price nor the value of all orders. For revenue, multiply ROW BY ROW first, then add. Each row has its own quantity-and-price pair, so calculate each row's revenue before calculating the grand total.
A second common mistake is trying to calculate revenue BEFORE the join. Until the matching price is next to qty, you can calculate only how many units were sold, not how much revenue they generated.
QUERY: Multiplying one total by another is the cheapest way to get a big, impressive number that means absolutely nothing. I've tested it. Repeatedly.
product_id is unique in the catalog, and every order refers to an existing product. First, predict how many rows there will be after the merge and store your prediction in rows_after; then check it with code. Next, calculate the archive's total revenue (total_revenue) and find the product with the highest total revenue (top_product).orders_raw, the product key is called pid; in catalog, it's called id; and both tables contain a name column (in the orders it is the CUSTOMER, in the catalog it is the PRODUCT). Join them so the column names remain clear, using the suffixes _customer and _product. Then calculate revenue by customer (revenue_by_customer) and find the biggest spender (top_customer).orders contains three rows with product_id = 103, while the products catalog contains exactly one row with product_id = 103. What happens when you run orders.merge(products, on='product_id')?merge, the result contains columns named name_x and name_y. What does that mean?A note for anyone who completed the SQL course. Everything above is a JOIN in a different : on= specifies a shared key and is similar to ON/USING, while left_on/right_on is like ON a.pid = b.id. The suffixes parameter automatically distinguishes same-named non-key columns; in SQL, you'd usually handle that with table or rename the columns in SELECT.
One difference is worth remembering: in SQL, the optimizer can change the physical join order while preserving the query's meaning. In pandas, you choose the sequence of each merge, and every join result is created in memory. If you save an intermediate DataFrame to a variable, you can print it, measure it, and inspect it. Here, you are responsible for checking the joins rather than the .
Key takeaways
mergeis an operation on two tables: it finds matching key values and combines columns from the corresponding rows. If one key value matches multiple rows, the result can contain multiple rows too.- Choose a key by meaning, not by name. The first check for a lookup table is
products['product_id'].is_unique. - In a many-to-one relationship, one catalog row can match any number of log rows, and its values are copied into every matching row. The catalog itself does not change.
- With an
innerjoin, as long as the key on the right is unique and every row on the left has a match, the row count does not change:mergeonly adds columns. The stays the same: one row = one order. - If the key has different names, use
left_on/right_on(both columns remain in the result). If non-key column names collide, pandas creates_x/_y; you can prevent that withsuffixesor by narrowing the lookup table to the columns you need. - After the join, calculate
revenue = qty * pricerow by row and only then apply.sum(). Do not multiply column totals together.
Next: what happens when not every row finds a match.