Left and Right Joins
Perform left and right joins to preserve all rows from one table while matching records from another.
Asymmetric Joins
Inner and outer joins treat both DataFrames symmetrically. But often you want to preserve all records from one table while enriching them with data from another. This is where left joins and right joins come in. These asymmetric joins are extremely common in analytics: keep all transactions, add product names where available; keep all users, add their last purchase date if they have one.
Left Join: Preserve All Left Rows
A left join (how='left') keeps every row from the left DataFrame. For rows that find a matching key in the right DataFrame, the right columns are filled with the matched values. For rows with no match, the right columns are filled with NaN. The row count of the result always equals the row count of the left DataFrame (assuming no duplicate keys).
import pandas as pd
orders = pd.DataFrame({
'order_id': [1, 2, 3, 4],
'customer_id': [101, 102, 101, 999],
'amount': [250, 80, 320, 150]
})
customers = pd.DataFrame({
'customer_id': [101, 102, 103],
'name': ['Alice', 'Bob', 'Carol']
})
result = pd.merge(orders, customers, on='customer_id', how='left')
print(result)
# All 4 orders kept; order with customer_id=999 gets NaN for name