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

Left/right/outer join

Choose how unmatched rows are treated: keep all left rows, all right rows, or everything.

In this page:

  1. Left/right/outer join
Syntax
python
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

python
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Choosing the wrong side for left versus right
  2. Ignoring NaN produced by unmatched rows
  3. 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:

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.