← Back to Pandas Course | Chapter 8: Merging & Joining | Lesson 5 of 7

merge on multiple keys

Pass a list of columns to on to match rows only when several columns all agree.

In this page:

  1. merge on multiple keys
Syntax
python
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

python
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
  1. Forgetting one key and getting duplicates
  2. Mismatched dtypes
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.