Sub topic 2
Your first merge
This chapter assumes you can build DataFrames, select columns, and read a DataFrame index. It also assumes you know that a key is a column whose values identify rows in another table. Here you run a basic merge and read its result.
What merge does
merge combines two DataFrames by matching values in a key column. For each row in the left table, pandas looks for rows in the right table with the same key value. Each match becomes one row in the result, with the columns of both tables side by side.
This is how a database join works. If you know SQL, merge is JOIN ... ON.
A first example
The customers table has one row per customer. The orders table has one row per order, and each order records which customer placed it.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
result = customers.merge(orders, on="customer_id")
print(result)The output is:
customer_id name order_id amount
0 1 Ana 10 25.0
1 1 Ana 11 40.0
2 3 Chen 12 15.5Three things to notice:
- Ana appears twice because she has two orders. Her row from
customersis repeated for each match. - Ben is missing because he has no orders.
- Order 13 is missing because customer 4 is not in
customers.
By default, merge keeps only keys found in both tables. This is an inner join. The next chapter covers the other join types.
Two ways to write the same call
merge exists as a method and as a top-level function. These two lines give the same result:
customers.merge(orders, on="customer_id")
pd.merge(customers, orders, on="customer_id")The first form chains well after other method calls. The second makes the two tables look equal. Use whichever reads better in your code. The table you call the method on is the left table.
What happens to the index and column order
When you merge on columns, pandas ignores both original indexes and gives the result a fresh RangeIndex (0, 1, 2, and so on). If your row labels carry meaning, move them into a column before merging.
The key column appears once, followed by the remaining columns of the left table and then those of the right. Rows follow the order of the left table's keys.
Always pass `on` explicitly
If you leave out on, pandas merges on every column name the two tables share. That can change silently when someone adds a column to one table. Naming the key makes the merge's intent clear and keeps it stable.
Common errors
| Symptom | Likely cause |
|---|---|
| `KeyError: 'customer_id'` | The column is missing from one table, or its name has different spelling, case, or whitespace. |
| `MergeError: No common columns to perform merge on` | You left out `on` and the tables share no column names. |
| Fewer rows than expected | The default inner join dropped keys that appear in only one table. |
| More rows than expected | A key repeats in one table, so its rows are duplicated. |
Before trusting a merge, compare len(result) with the row counts of the inputs. Here, 3 rows from 3 customers and 4 orders is a reason to check why, and the answer is the dropped and repeated keys above.
Exercise
Exercise
Using the tables above, what does orders.merge(customers, on="customerid") return, compared with customers.merge(orders, on="customerid")? Give the number of rows, the order of the columns, and which table's keys set the row order.
Show answer
Both calls return 3 rows, because the inner join keeps only customerid values 1 and 3, which appear in both tables. Swapping the tables changes the layout. The columns now start with the orders columns (customerid, orderid, amount, with customerid first as the key) and end with name. Rows follow the order of the orders table, so the two Ana rows (orders 10 and 11) come first, then Chen (order 12).