Sub topic 3
Inner, left, right, and outer joins
This chapter explains the how argument of merge. It decides which rows survive when the keys of the two tables don't match perfectly. It assumes you can build DataFrames, select columns, and read the index, and that you have seen a basic merge on a shared key column. It also assumes you know that NaN marks a missing value in a column.
What a join type decides
Every merge compares the key values in the left table with the key values in the right table. Three groups of rows can result:
- Rows whose key appears in both tables. These are the matched rows.
- Rows whose key appears only in the left table.
- Rows whose key appears only in the right table.
The join type chooses which of these groups appear in the result. Matched rows are always included. Unmatched rows are included or dropped depending on how. When an unmatched row is kept, the columns that came from the other table are filled with NaN.
| `how` | Matched rows | Left-only rows | Right-only rows | Row order |
|---|---|---|---|---|
| `"inner"` (default) | kept | dropped | dropped | order of the left keys |
| `"left"` | kept | kept | dropped | order of the left keys |
| `"right"` | kept | dropped | kept | order of the right keys |
| `"outer"` | kept | kept | kept | keys sorted lexicographically |
The running example
The example uses three customers and four orders. Customer 2 (Ben) has no orders. Order 13 belongs to customer 4, who is not in the customer table. Customer 1 (Ana) has two orders.
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],
})
inner = customers.merge(orders, on="customer_id", how="inner")
left = customers.merge(orders, on="customer_id", how="left")
right = customers.merge(orders, on="customer_id", how="right")
outer = customers.merge(orders, on="customer_id", how="outer", indicator=True)
for label, frame in [("inner", inner), ("left", left), ("right", right), ("outer", outer)]:
print(label, len(frame))
print(frame, end="\n\n")The four frames have 3, 4, 4, and 5 rows.
Inner join
An inner join keeps only the keys present in both tables.
customer_id name order_id amount
0 1 Ana 10 25.0
1 1 Ana 11 40.0
2 3 Chen 12 15.5Ben is gone because he has no orders. Order 13 is gone because its customer is missing from customers. Ana appears twice because each of her two orders matches her one customer row.
Use an inner join when you only want complete records, for example an analysis of purchases that must have customer details. The cost is that rows vanish without any warning. If you expected every order to have a customer, an inner join hides the failure.
Left join
A left join keeps every row of the left table and attaches matching rows from the right table.
customer_id name order_id amount
0 1 Ana 10.0 25.0
1 1 Ana 11.0 40.0
2 2 Ben NaN NaN
3 3 Chen 12.0 15.5Ben is kept, and his order_id and amount are NaN. Order 13 is still dropped, because the right table's unmatched rows are discarded.
Notice that order_id changed from int64 to float64. A NumPy integer column cannot hold NaN, so pandas converts the column to floats once a missing value appears. If you want integers back, convert to the nullable type with left["order_id"].astype("Int64"). Then the missing entry becomes <NA>.
A left join is the usual choice when the left table is your main table and the right table only adds information. Think of enriching a list of customers with their order data, or a list of transactions with product names.
A common misunderstanding is that a left join always returns the same number of rows as the left table. It returns at least that many. Ana's one row became two, because she matched two orders. The row count rule is covered in the chapter on cardinality, but keep it in mind here: the left join guarantees that no left row disappears, not that none is duplicated.
Right join
A right join is the mirror image. It keeps every row of the right table.
customer_id name order_id amount
0 1 Ana 10 25.0
1 1 Ana 11 40.0
2 3 Chen 12 15.5
3 4 NaN 13 60.0Order 13 is kept with a missing name, and Ben is dropped. The key column shows 4, because pandas fills the key from whichever side has it. Here order_id stays an integer, since no order row is missing.
A right join is the same operation as a left join with the two tables swapped. Most people write left joins and put the table they want to keep first, because the code then reads from left to right in the order of importance. The only visible difference is the column order and row order of the result. This code shows that the two forms hold the same data:
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],
})
a = customers.merge(orders, on="customer_id", how="right")
b = orders.merge(customers, on="customer_id", how="left")
print(a.equals(b[a.columns]))This prints True, once the columns of b are put in the same order as a.
Outer join
An outer join keeps everything from both tables.
customer_id name order_id amount _merge
0 1 Ana 10.0 25.0 both
1 1 Ana 11.0 40.0 both
2 2 Ben NaN NaN left_only
3 3 Chen 12.0 15.5 both
4 4 NaN 13.0 60.0 right_onlyBoth unmatched rows appear: Ben with missing order columns and order 13 with a missing name. The result is sorted by key. The _merge column comes from indicator=True. It labels each row both, left_only, or right_only, so you can see how each row was formed.
Outer joins are useful for reconciliation, where you compare two sources and want to see everything that does not agree. They are a poor default for building a final table, because they produce NaN on both sides.
Finding unmatched rows with an anti-join
Pandas has no how="anti" option, but an outer merge with indicator=True gives you the same result. Filter on _merge to list rows that exist in only one 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],
})
audit = customers.merge(orders, on="customer_id", how="outer", indicator=True)
no_orders = audit.loc[audit["_merge"] == "left_only", ["customer_id", "name"]]
orphans = audit.loc[audit["_merge"] == "right_only", ["customer_id", "order_id"]]
print(no_orders)
print(orphans)The output is:
customer_id name
2 2 Ben
customer_id order_id
4 4 13.0The first frame lists customers without orders. The second lists orders whose customer is unknown, which in real data usually points to a data quality problem. This pattern is the foundation of the auditing techniques in a later chapter.
Counting rows to check your expectation
You can predict the row count before running a merge. Let m be the number of matched row pairs, which is the sum over shared keys of (left count × right count). In the example, Ana contributes 1 × 2 and Chen 1 × 1, so m = 3. Then:
- inner =
m - left =
m+ left rows with no match (here 1, Ben) - right =
m+ right rows with no match (here 1, order 13) - outer =
m+ both kinds of unmatched rows
That gives 3, 4, 4, and 5, which agrees with the printed lengths. If the real count differs from your prediction, duplicate keys or mismatched key values are the usual cause.
Choosing a join type
Decide by asking which table's rows must not be lost.
- If both tables must be complete for the row to be useful, use
inner. - If one table is the main table and the other only adds columns, put the main table on the left and use
left. - If you are comparing two sources and need to see every disagreement, use
outerwithindicator=True. - Use
rightonly when the code reads more naturally that way. It adds nothing a swappedleftdoesn't.
Common errors
- Surprise missing rows. An inner join dropped rows you wanted. Check the unmatched keys with an outer merge and
indicator=True. - Surprise
NaNcolumns. A left join produced manyNaNvalues because the keys differ in dtype or spelling, so almost nothing matched. The result has the right number of rows but no useful data. - Float columns after a join. Integer columns that gain missing values become floats. Convert them to
Int64if you need integers. - Assuming the row order. Only rely on the order table above. Sort explicitly if the order matters.
Exercise
Table a has keys [1, 2, 3, 3] and table b has keys [3, 4, 4]. How many rows do an inner, left, right, and outer merge on the key return?
Show answer
Only key 3 is shared. It appears twice in a and once in b, so the matched pairs are 2 × 1 = 2. Inner: 2 rows. Left: 2 matched plus unmatched keys 1 and 2 from a, so 4 rows. Right: 2 matched plus the two rows with key 4 from b, so 4 rows. Outer: 2 matched plus 2 left-only plus 2 right-only, so 6 rows.
Exercise
You have a customers table and an orders table. Write the merge call that returns only the customers who have never placed an order, as a DataFrame with the columns customer_id and name.
Show answer
Use an outer or left merge with indicator=True and keep the left_only rows: m = customers.merge(orders, on="customer_id", how="left", indicator=True) then m.loc[m["_merge"] == "left_only", ["customer_id", "name"]]. A left merge is enough here, because customers without orders appear as left_only.