Pandas Merge: The Ultimate Guide
If you know JOIN in SQL, you already know 90% of this. Learn how to
combine DataFrames efficiently.
Basic Syntax
The `merge()` function is the most versatile way to combine data.
import pandas as pd
# The Basic Command
merged_df = pd.merge(df1, df2, on='key_column', how='inner')
- df1, df2: The DataFrames to merge.
- on: The column name to join on (must exist in both).
- how: The type of join ('inner', 'outer', 'left', 'right').
The 4 Types of Joins
INNER JOIN
Keeps only keys that are in BOTH tables. (Default)
LEFT JOIN
Keeps ALL keys from Left table, matches from Right. Fills NaN if missing.
RIGHT JOIN
Keeps ALL keys from Right table, matches from Left.
OUTER JOIN
Keeps ALL keys from BOTH tables. Fills NaN everywhere missing.
Joining on Different Column Names
Often, your keys have different names (e.g., "id" vs "employee_id"). You don't need to rename columns.
# Left DataFrame has 'id', Right DataFrame has 'emp_id'
merged_df = pd.merge(
df1,
df2,
left_on='id',
right_on='emp_id',
how='inner'
)
Common Pitfall: Duplicate Keys
If your key column has duplicates in both tables, Pandas performs a Cartesian product (multiplies rows). If Table A has 3 rows for ID=1, and Table B has 2 rows for ID=1, the result will have 3 * 2 = 6 rows.
Tip: Always check df.shape before and after merging
to ensure you didn't accidentally explode your dataset size.