Left/right/outer join
Choose how unmatched rows are treated: keep all left rows, all right rows, or everything.
In this page:
Syntax
pd.merge(left, right, on="key_column", how="left")
pd.merge(left, right, on="key_column", how="outer")
Left/right/outer join
how="left" keeps every row of the left table, how="right" keeps every right row, and how="outer" keeps all rows from both. Missing partners are filled with NaN. The indicator=True option adds a column showing where each row came from.
Note:
indicator=True is great for auditing joins.
Example: Left/right/outer join
import pandas as pd
emp = pd.DataFrame({"name": ["Ann", "Bob", "Cy"], "dept_id": [10, 20, 30]})
dept = pd.DataFrame({"dept_id": [10, 20, 40], "dept": ["Sales", "Tech", "HR"]})
print(emp.merge(dept, on="dept_id", how="left"))
print(emp.merge(dept, on="dept_id", how="outer", indicator=True))
# Output:
# name dept_id dept
# 0 Ann 10 Sales
# 1 Bob 20 Tech
# 2 Cy 30 NaN
# name dept_id dept _merge
# 0 Ann 10 Sales both
# 1 Bob 20 Tech both
# 2 Cy 30 NaN left_only
# 3 NaN 40 HR right_only
Related Topics
Common Mistakes
- Choosing the wrong side for left versus right
- Ignoring NaN produced by unmatched rows
- Forgetting outer joins can grow the result
Chapter Summary
- left keeps all left rows
- right keeps all right rows
- outer keeps all rows
- indicator shows the source
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: