merge on multiple keys
Pass a list of columns to on to match rows only when several columns all agree.
In this page:
Syntax
merged = pd.merge(left, right, on=["key1", "key2"])
merge on multiple keys
merge(on=["a", "b"]) requires every listed key to match. This is essential when no single column identifies a row, such as year plus region. All keys must exist in both tables or you can use left_on and right_on lists.
Note:
Make sure key dtypes match on both sides.
Example: merge on multiple keys
import pandas as pd
a = pd.DataFrame({"year": [2023, 2023, 2024], "region": ["N", "S", "N"], "sales": [10, 20, 30]})
b = pd.DataFrame({"year": [2023, 2024, 2024], "region": ["N", "N", "S"], "target": [12, 28, 15]})
print(a.merge(b, on=["year", "region"], how="left"))
# Output:
# year region sales target
# 0 2023 N 10 12.0
# 1 2023 S 20 NaN
# 2 2024 N 30 28.0
Related Topics
Common Mistakes
- Forgetting one key and getting duplicates
- Mismatched dtypes
- Assuming order of keys matters
Chapter Summary
- on takes a list of keys
- All keys must match
- Use left_on/right_on for different names
- Dtypes must agree
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: