Sub topic 6
Joining on the index with join
This chapter assumes you can build DataFrames, know what the index is and how to name it, and have run a basic merge with how and on. Here you will use DataFrame.join and the left_index and right_index options of merge. Both match rows by index labels instead of by ordinary columns.
Why join on the index
A DataFrame index is a set of row labels. When a table is already keyed by something meaningful, such as a product ID, a date, or a user ID, the index is the natural place to match on. It has three practical advantages.
- Lookup tables often have exactly one row per key. Storing that key as the index documents the fact and makes the table behave like a dictionary.
- The index keeps its name, so
product_idis visible in the printed output. joinhas short syntax for the common case: attach the columns of one table to another.
join is a convenience wrapper around merge. It calls the same machinery with different defaults.
| Behavior | `DataFrame.join` | `DataFrame.merge` |
|---|---|---|
| Default `how` | `"left"` | `"inner"` |
| Right-hand key | Always the right table's index | A column (`on`, `right_on`) or the index (`right_index=True`) |
| Left-hand key | The left index, or a column named in `on` | A column (`on`, `left_on`) or the index (`left_index=True`) |
| Overlapping columns | Raises `ValueError` unless `lsuffix` or `rsuffix` is given | Adds `_x` and `_y` by default, or whatever `suffixes` says |
| Index of the result | Keeps the left index when `how="left"` | Usually a new `RangeIndex` when keys are columns |
The difference in defaults is the usual source of surprise. A join keeps every left row. A merge drops rows without a match.
Joining a column against an index
The most common pattern has a transactional table with a key column on the left and a lookup table indexed by that key on the right. Pass the left column name to on.
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)The output is:
sku name qty price
0 1 Pen 3 1.5
1 2 Book 1 12.0
2 2 Book 2 12.0The sku column of items is matched against the index of prices. The two names do not need to agree, because the right side is always identified by position in the index, not by name. The result keeps the left index (0, 1, 2), and all three rows survive. The row count equals the left row count, since each sku appears once in prices.
If you leave out on, join matches the left index against the right index. That is rarely what you want when the left table has the key in a column.
stock = pd.DataFrame(
{"on_hand": [40, 5, 0]},
index=pd.Index([1, 2, 3], name="product_id"),
)
print(prices.join(stock))
print(prices.join(stock, how="outer"))The first call is a left join, so product 3 is dropped. The second call is an outer join and returns:
price on_hand
product_id
1 1.5 40
2 12.0 5
3 NaN 0Product 3 has no price, so price is NaN. Index-to-index joins keep the shared index name, which is why product_id appears above the rows.
The merge equivalent
Every join can be written as a merge with index flags. The following call is the same logical operation as items.join(prices, on="sku"), except for the how default:
same = items.merge(prices, left_on="sku", right_index=True, how="left")
print(same)You will reach for merge instead of join when you want one of these:
- An inner join without spelling out
how. - The
suffixesparameter, with a single name pair for both sides. - A key that is the index on the left and a column on the right (
left_index=True, right_on="col"). - Both sides indexed, with the options of
mergein a single call (left_index=True, right_index=True).
When a key is an index on one side and a column on the other, the label of the index is not required to match the column name. Each side is matched by its own flag, so you only need to give merge one flag per side.
Overlapping column names
join refuses to guess when both tables share a column name.
a = pd.DataFrame({"score": [1, 2]}, index=["x", "y"])
b = pd.DataFrame({"score": [10, 20]}, index=["x", "y"])
try:
a.join(b)
except ValueError as err:
print("join failed:", err)
print(a.join(b, lsuffix="_a", rsuffix="_b"))The first call raises ValueError because both frames contain score. The second call renames the left column to score_a and the right column to score_b. Note the parameter names: join uses lsuffix and rsuffix, whereas merge uses a single suffixes=("_x", "_y") tuple. Mixing them up produces a TypeError.
Suffixes are applied only to columns that appear on both sides. With join(on=...), the left key column is not renamed.
Joining several tables at once
join accepts a list of DataFrames. Each one is joined by index, in order, to the caller.
weights = pd.DataFrame(
{"grams": [5, 450]},
index=pd.Index([1, 2], name="product_id"),
)
catalog = prices.join([stock, weights], how="outer")
print(catalog)This is shorter than two chained calls. The list form has restrictions:
- It only joins on indexes. The
onargument is not allowed with a list. - The suffix arguments are not allowed either, so any overlapping column name raises an error.
- All the frames in the list are joined with the same
how.
If any of those restrictions get in the way, chain individual join or merge calls.
Joining on a MultiIndex
A right-hand table can have a MultiIndex, which has several levels. Pass a list of left columns to on. They must come in the same order as the index levels.
stock_by_store = pd.DataFrame(
{"on_hand": [40, 5, 12]},
index=pd.MultiIndex.from_tuples(
[("north", 1), ("north", 2), ("south", 2)],
names=["store", "sku"],
),
)
sales = pd.DataFrame({
"store": ["north", "south", "south"],
"sku": [1, 2, 1],
"qty": [3, 1, 2],
})
print(sales.join(stock_by_store, on=["store", "sku"]))The third sale (south, SKU 1) has no stock record, so its on_hand is NaN. Because of that NaN, the column becomes float64 and the other values print as 40.0 and 12.0. This is a general effect of left joins: integer columns from the right side turn into floats when any row fails to match.
Row counts and validation
An index does not have to be unique. If the right index contains the same label twice, every matching left row is repeated, and the result can have more rows than the left table. The same cardinality rules from the previous chapters apply, with the index playing the role of the key.
join accepts the validate argument, so you can assert the relationship you expect.
checked = items.join(prices, on="sku", validate="many_to_one")
print(len(checked))Here many rows on the left may share a sku, but each sku must occur once in the index of prices. If someone later adds a duplicate price row, this call raises MergeError instead of silently inflating the totals. You can also check the index directly before joining with prices.index.is_unique.
Common errors
- No matches at all. If the left column is
int64and the index holds strings such as"1", no keys match and every right-hand value isNaN. Compareitems["sku"].dtypewithprices.index.dtype, and convert withastypebefore joining. - Forgetting
on.items.join(prices)compares the left row labels (0, 1, 2) with the right index (1, 2). It produces a plausible but wrong result, because labels 1 and 2 happen to exist. - Expecting an inner join. A
joinkeeps unmatched left rows. Usehow="inner"when you want them dropped. - Lost index in merge. With a column key,
mergeusually returns a freshRangeIndex. If the index carried information, callreset_index()before the merge or usejoin. - Key stored as a column on the right.
joincannot use a right-hand column. Callright.set_index("key")first, or usemerge.
Exercises
Exercise
You run orders.join(customers) where orders has a customer_id column and a default RangeIndex, and customers is indexed by customer_id. The result has many NaN values in the customer columns, yet no error appears. What went wrong, and how do you fix it?
Show answer
Without on, join matches the left index (0, 1, 2, ...) against the right index (customer IDs). Only IDs that happen to equal the row positions match, so most rows get NaN. Fix it with orders.join(customers, on="customer_id").
Exercise
a and b both have a column named total and share an index. a.join(b) raises an error. Write a call that keeps both columns, and say what happens to the column names.
Show answer
a.join(b, lsuffix="_a", rsuffix="_b"). The left total becomes total_a and the right total becomes total_b. Columns that appear on only one side keep their names.