Sub topic 6
Joining on the index with join
This chapter assumes you know how merge works, including join types, and that you understand what a DataFrame index is. Here you will use DataFrame.join, which matches rows by index labels.
What join does
DataFrame.join is a shortcut for the common case where the right-hand table is keyed by its index. It differs from merge in three ways:
| Behavior | `merge` | `join` |
|---|---|---|
| Default `how` | `"inner"` | `"left"` |
| Right table is matched on | Columns (or index with `right_index=True`) | Always its index |
| Left table is matched on | Columns (or index) | Its index, or a column named in `on=` |
The right table's index is always the key. The left side can use either its index or a column.
Matching a column against the index
Suppose prices is indexed by product ID, and items has a plain sku column holding the same IDs.
import pandas as pd
items = pd.DataFrame({
"sku": [1, 2, 2],
"name": ["Pen", "Book", "Book"],
"qty": [3, 1, 2],
})
prices = pd.DataFrame(
{"price": [1.5, 12.0]},
index=pd.Index([1, 2], name="product_id"),
)
with_prices = items.join(prices, on="sku")
print(with_prices) sku name qty price
0 1 Pen 3 1.5
1 2 Book 1 12.0
2 2 Book 2 12.0The result keeps the index of items. Each row of items is a lookup into prices, so a repeated sku repeats the price. If a sku had no match in prices, price would be NaN and the row would stay, because the default is a left join.
Joining index to index
Without on, both sides are matched by index.
stock = pd.DataFrame(
{"stock": [40, 7]},
index=pd.Index([1, 2], name="product_id"),
)
combined = prices.join(stock)
print(combined) price stock
product_id
1 1.5 40
2 12.0 7This is the same as the longer merge form:
same = prices.merge(stock, left_index=True, right_index=True, how="left")Use how="inner", "right", or "outer" with join exactly as you would with merge.
Overlapping column names
merge adds _x and _y automatically. join does not. If both tables share a column name, it raises a ValueError. Pass lsuffix, rsuffix, or both.
a = pd.DataFrame({"v": [1, 2]}, index=[1, 2])
b = pd.DataFrame({"v": [10, 20]}, index=[1, 2])
print(a.join(b, lsuffix="_a", rsuffix="_b")) v_a v_b
1 1 10
2 2 20Common errors
- Index labels do not line up. If the index is a default
RangeIndexon one side and real IDs on the other, nothing matches and you get allNaN. Check withdf.indexbefore joining. - Dtype mismatch. An index of strings like
"1"never matches an integer1. Convert one side first. - Duplicate index labels on the right. Each matching right row produces an output row, so the result can have more rows than the left table. Check
prices.index.is_uniquewhen you expect a lookup. - Forgetting that the left index is kept. With
on=, the result keeps the left table's index, not the key.
When to prefer which
Use join when the right table is already indexed by the key, or when you want a quick left join of tables that share an index. Use merge when the key sits in columns on both sides, or when you want an inner join by default.
Exercise
orders has a column cust with values [1, 1, 5] and the default RangeIndex. customers has index [1, 2, 3] and a column tier. What does orders.join(customers, on="cust") return for the rows, and how many rows does it have?
Show answer
It returns 3 rows, one per order, because the default is a left join. The two rows with cust 1 get the matching tier. The row with cust 5 has no match in the customers index, so its tier is NaN.