Sub topic 3
Inner, left, right, and outer joins
This chapter assumes you can build DataFrames, know what a key column is, and have run merge once with on=. It covers the how argument, which decides what happens to rows whose key has no match in the other table.
The four join types
merge takes a how argument. The two tables are called left (the one you call merge on) and right (the one you pass in).
| `how` | Rows kept |
|---|---|
| `"inner"` (default) | Keys present in both tables |
| `"left"` | Every left row, plus matches from the right |
| `"right"` | Every right row, plus matches from the left |
| `"outer"` | Every row from both tables |
Where a row has no match, pandas fills the other table's columns with NaN.
Comparing row counts
The sample data has three customers and four orders. Customer 2 (Ben) has no orders. Order 13 belongs to customer 4, who is not in the customer table.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
for how in ["inner", "left", "right", "outer"]:
result = customers.merge(orders, on="customer_id", how=how)
print(how, len(result))This prints 3 for inner, 4 for left, 4 for right, and 5 for outer. Ana matches two orders, so she produces two rows in every join type.
Left joins keep the table you care about
A left join is the usual choice when one table is the main list and the other adds detail.
left = customers.merge(orders, on="customer_id", how="left")
print(left)Ben appears once, with NaN in order_id and amount. Because NaN is a float, order_id changes from integer to float (10.0, 11.0). Convert it back with the nullable Int64 dtype if you need integers.
Outer joins and the indicator column
An outer join keeps unmatched rows from both sides. Add indicator=True to see where each row came from.
outer = customers.merge(orders, on="customer_id", how="outer", indicator=True)
print(outer[["customer_id", "name", "order_id", "_merge"]])The _merge column holds both, left_only, or right_only. Here Ben is left_only and customer 4 is right_only. Customer 4's name is NaN because that customer is missing from the left table.
You can use the indicator to filter. This keeps only the rows that failed to match:
unmatched = outer[outer["_merge"] != "both"]
print(unmatched)Choosing a join type
Ask which rows you cannot afford to lose.
- Use inner when only complete records make sense, such as orders that have a known customer.
- Use left when the left table is your master list and missing detail is acceptable.
- Use outer when you are reconciling two sources and want to see every disagreement.
Common errors
- Using the default inner join and silently losing rows. Compare
len()before and after. - Reading
NaNas bad data. After a left or outer join, it often only means there was no match. - Expecting the row count to equal the left table's. Duplicate keys in the right table add rows, which a later chapter covers.
Exercise
Using the tables above, you need a report listing every customer, including those who never ordered. Which join type do you use, and how many rows does it return?
Show answer
Use a left join, with customers as the left table. It returns 4 rows: Ana twice, Ben with NaN order columns, and Chen.
Exercise
How do you list the orders whose customer_id is missing from the customers table?
Show answer
Run customers.merge(orders, on="customerid", how="outer", indicator=True) and keep the rows where merge equals "right_only". This gives order 13 for customer 4.