Merging and Joining
Real data is spread over several tables: orders in one, customers in another, products in a third. To answer "how much did each city spend?" you have to join them on a shared key, exactly like a SQL JOIN. In pandas this is pd.merge() (or the method df.merge()).
Our two tables
import pandas as pd
customers = pd.DataFrame({
"cust_id": [1, 2, 3, 4],
"name": ["Arlo", "Bea", "Cato", "Dina"],
"city": ["Lyon", "Turin", "Lyon", "Ghent"],
})
orders = pd.DataFrame({
"order_id": [501, 502, 503, 504, 505],
"cust_id": [2, 1, 2, 5, 3],
"total": [42.0, 18.5, 77.0, 12.0, 30.0],
})
print(customers)
print(orders) cust_id name city
0 1 Arlo Lyon
1 2 Bea Turin
2 3 Cato Lyon
3 4 Dina Ghent
order_id cust_id total
0 501 2 42.0
1 502 1 18.5
2 503 2 77.0
3 504 5 12.0
4 505 3 30.0
Customer 4 (Dina) never ordered, and order 504 belongs to customer 5, who isn't in the customer table. These mismatches are where the join types differ.
Inner join (the default)
merge matches rows where the key appears in both tables:
import pandas as pd
customers = pd.DataFrame({
"cust_id": [1, 2, 3, 4],
"name": ["Arlo", "Bea", "Cato", "Dina"],
"city": ["Lyon", "Turin", "Lyon", "Ghent"],
})
orders = pd.DataFrame({
"order_id": [501, 502, 503, 504, 505],
"cust_id": [2, 1, 2, 5, 3],
"total": [42.0, 18.5, 77.0, 12.0, 30.0],
})
joined = orders.merge(customers, on="cust_id")
print(joined)
print(joined.groupby("city")["total"].sum()) order_id cust_id total name city
0 501 2 42.0 Bea Turin
1 502 1 18.5 Arlo Lyon
2 503 2 77.0 Bea Turin
3 505 3 30.0 Cato Lyon
city
Lyon 48.5
Turin 119.0
Name: total, dtype: float64
Order 504 and Dina both vanished because they had no partner. Bea appears twice because she has two orders: a merge repeats rows as needed.
The four join types
how= |
Keeps |
|---|---|
"inner" (default) |
only keys found in both tables |
"left" |
every row of the left table; NaN where the right has no match |
"right" |
every row of the right table |
"outer" |
every key from either table |
import pandas as pd
customers = pd.DataFrame({
"cust_id": [1, 2, 3, 4],
"name": ["Arlo", "Bea", "Cato", "Dina"],
})
orders = pd.DataFrame({
"order_id": [501, 502, 503, 504, 505],
"cust_id": [2, 1, 2, 5, 3],
"total": [42.0, 18.5, 77.0, 12.0, 30.0],
})
print(customers.merge(orders, on="cust_id", how="left"))
print(customers.merge(orders, on="cust_id", how="outer", indicator=True)) cust_id name order_id total
0 1 Arlo 502.0 18.5
1 2 Bea 501.0 42.0
2 2 Bea 503.0 77.0
3 3 Cato 505.0 30.0
4 4 Dina NaN NaN
cust_id name order_id total _merge
0 1 Arlo 502.0 18.5 both
1 2 Bea 501.0 42.0 both
2 2 Bea 503.0 77.0 both
3 3 Cato 505.0 30.0 both
4 4 Dina NaN NaN left_only
5 5 NaN 504.0 12.0 right_only
indicator=True adds a _merge column telling you where each row came from (both, left_only, right_only), which is a great way to find unmatched records.
Different key names and overlapping columns
If the key has a different name in each table, use left_on and right_on. If both tables have other columns with the same name, pandas adds the suffixes _x and _y; choose better ones with suffixes=:
import pandas as pd
products = pd.DataFrame({"sku": ["P1", "P2", "P3"], "price": [9.5, 4.0, 12.0]})
lines = pd.DataFrame({
"product_code": ["P2", "P1", "P2"],
"qty": [3, 1, 2],
"price": [3.5, 9.5, 4.0], # price actually charged
})
m = lines.merge(products, left_on="product_code", right_on="sku",
suffixes=("_charged", "_list"))
m["discount"] = m["price_list"] - m["price_charged"]
print(m) product_code qty price_charged sku price_list discount
0 P2 3 3.5 P2 4.0 0.5
1 P1 1 9.5 P1 9.5 0.0
2 P2 2 4.0 P2 4.0 0.0
Joining on the index
df.join() is a shortcut that joins on the index of the other table, convenient when your lookup table is indexed by its key:
import pandas as pd
rates = pd.DataFrame({"eur_rate": [1.0, 0.92, 0.0061]}, index=["EUR", "USD", "JPY"])
payments = pd.DataFrame({"amount": [100, 2500, 40], "currency": ["USD", "JPY", "EUR"]})
payments = payments.join(rates, on="currency")
payments["amount_eur"] = (payments["amount"] * payments["eur_rate"]).round(2)
print(payments) amount currency eur_rate amount_eur
0 100 USD 0.9200 92.00
1 2500 JPY 0.0061 15.25
2 40 EUR 1.0000 40.00
Validating a merge
A surprise many-to-many match can multiply your rows silently. validate= makes pandas check the relationship and raise an error if it's wrong:
import pandas as pd
left = pd.DataFrame({"k": ["a", "b"], "x": [1, 2]})
right = pd.DataFrame({"k": ["a", "a", "b"], "y": [10, 11, 20]})
print(len(left.merge(right, on="k", validate="one_to_many")))
try:
left.merge(right, on="k", validate="one_to_one")
except Exception as err:
print(type(err).__name__, "-", err)3
MergeError - Merge keys are not unique in right dataset; not a one-to-one merge
Tip: After every merge, compare
len()before and after. An unexpected increase almost always means duplicate keys.
Test yourself
Which join keeps every row of the left table, even without a match?
- inner
- left
- right
- cross
What does indicator=True add to a merge result?
- A row number
- A
_mergecolumn saying which table each row came from - A count of matches
- Nothing visible
Both tables have a column price (not the key). What are they called after merging, by default?
- price and price
- price_x and price_y
- price_left and price_right
- price1 and price2