merge() inner join
merge combines two tables by matching values in a key column; an inner join keeps only rows found in both.
In this page:
Syntax
merged = pd.merge(left, right, on="key_column")
merge() inner join
pd.merge(left, right, on="key") is the Pandas version of SQL JOIN. The default how="inner" keeps only keys present in both tables. If key names differ, use left_on and right_on.
Note:
Use validate="one_to_one" to catch unexpected duplicate keys.
Example: merge() inner join
import pandas as pd
emp = pd.DataFrame({"emp_id": [1, 2, 3], "name": ["Ann", "Bob", "Cy"], "dept_id": [10, 20, 30]})
dept = pd.DataFrame({"dept_id": [10, 20, 40], "dept": ["Sales", "Tech", "HR"]})
print(pd.merge(emp, dept, on="dept_id"))
# Output:
# emp_id name dept_id dept
# 0 1 Ann 10 Sales
# 1 2 Bob 20 Tech
Related Topics
Common Mistakes
- Losing rows without realizing inner join drops unmatched keys
- Merging on keys with different dtypes
- Unexpected row multiplication from duplicate keys
Chapter Summary
- merge matches on key columns
- Default is inner join
- left_on and right_on handle different names
- Duplicate keys multiply rows
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: