Data analysis with pandas · Lesson 12 of 15
Merging and joining tables
Combine two tables on a shared column with pd.merge, choose inner, left or outer joins, spot rows with no match, and stack tables with concat.
Data often lives in several tables: orders in one, customer details in another, linked by a customer code. Merging puts them side by side, matching rows on that shared column (the key). Spreadsheet users know this as a lookup.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
print(orders)
print(customers)order cust amount 0 1 C1 40 1 2 C2 25 2 3 C1 60 3 4 C3 15 4 5 C9 30 cust name city 0 C1 Ana Porto 1 C2 Ben Leeds 2 C3 Chloe Lyon 3 C4 Dev Oslo
Order 5 has customer C9, who is not in the customer list; customer C4 (Dev) has no orders.
pd.merge
pd.merge(left, right, on="cust") finds, for each order, the customer row with the same code and adds its columns. By default it is an inner join: only rows with a match in both tables are kept, so order 5 disappears.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
both = pd.merge(orders, customers, on="cust")
print(both)order cust amount name city 0 1 C1 40 Ana Porto 1 2 C2 25 Ben Leeds 2 3 C1 60 Ana Porto 3 4 C3 15 Chloe Lyon
Left, right and outer joins
how="left": keep every row of the left table; missing details become NaN.how="right": keep every row of the right table.how="outer": keep everything from both sides.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
left = pd.merge(orders, customers, on="cust", how="left")
print(left)order cust amount name city 0 1 C1 40 Ana Porto 1 2 C2 25 Ben Leeds 2 3 C1 60 Ana Porto 3 4 C3 15 Chloe Lyon 4 5 C9 30 NaN NaN
Order 5 stays; its name and city are NaN because C9 is unknown.
indicator=True adds a _merge column that says where each row came from. It is the easiest way to find the rows that did not match, a common check when you clean data.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
full = pd.merge(orders, customers, on="cust", how="outer", indicator=True)
print(full[["order", "cust", "name", "_merge"]])order cust name _merge 0 1.0 C1 Ana both 1 3.0 C1 Ana both 2 2.0 C2 Ben both 3 4.0 C3 Chloe both 4 NaN C4 Dev right_only 5 5.0 C9 NaN left_only
left_only: an order with no customer. right_only: a customer with no order. The NaN turned order into decimals.
After the merge
Once the tables are joined, you can group by any column from either side, such as total spending per city. If the key has different names in the two tables, use left_on= and right_on= instead of on=.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
both = pd.merge(orders, customers, on="cust")
print(both.groupby("city")["amount"].sum())city Leeds 25 Lyon 15 Porto 100 Name: amount, dtype: int64
Stacking tables with concat
pd.concat([a, b]) puts tables with the same columns one under the other, for example January's and February's sales. ignore_index=True gives the result a fresh index.
import pandas as pd
jan = pd.DataFrame({"item": ["tea", "cake"], "sales": [120, 45]})
feb = pd.DataFrame({"item": ["tea", "jam"], "sales": [140, 20]})
both = pd.concat([jan, feb], ignore_index=True)
print(both)
print(both.groupby("item")["sales"].sum().to_dict()) item sales
0 tea 120
1 cake 45
2 tea 140
3 jam 20
{'cake': 45, 'jam': 20, 'tea': 260}✎ Exercise
Merge orders and customers so that every customer appears, even those with no orders (use the customers table as the left one). Print the name and amount columns.
Hint: pd.merge(customers, orders, on="cust", how="left") keeps every customer.
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
# your code here
Expected output:
name amount 0 Ana 40.0 1 Ana 60.0 2 Ben 25.0 3 Chloe 15.0 4 Dev NaN
Show a solution
import pandas as pd
orders = pd.DataFrame({
"order": [1, 2, 3, 4, 5],
"cust": ["C1", "C2", "C1", "C3", "C9"],
"amount": [40, 25, 60, 15, 30],
})
customers = pd.DataFrame({
"cust": ["C1", "C2", "C3", "C4"],
"name": ["Ana", "Ben", "Chloe", "Dev"],
"city": ["Porto", "Leeds", "Lyon", "Oslo"],
})
out = pd.merge(customers, orders, on="cust", how="left")
print(out[["name", "amount"]])name amount 0 Ana 40.0 1 Ana 60.0 2 Ben 25.0 3 Chloe 15.0 4 Dev NaN
Check yourself
1. Which join keeps only rows that match in both tables?
An inner join (the default of pd.merge) keeps only keys found on both sides.
2. After a left join, a customer detail is NaN. What does that mean?
A left join keeps every left row; where no right row matches, the new columns are filled with NaN.
3. What is pd.concat([jan, feb]) for?
concat stacks tables; merge matches them side by side.