Sub topic 4
Merging on differently named and multiple keys
This chapter assumes you can run a basic merge on a single shared column and choose a join type with how. It also assumes you know what a DataFrame column and a dtype are. Here you will handle two situations that real data produces often: the key has a different name in each table, or one column is not enough to identify a row.
Keys that have different names
The on argument requires the key column to exist in both DataFrames under the same name. Real tables often disagree. One table calls the identifier product_id, another calls it sku. Use left_on for the column name in the left DataFrame and right_on for the column name in the right DataFrame.
import pandas as pd
products = pd.DataFrame({
"product_id": [1, 2],
"name": ["Pen", "Book"],
"price": [1.5, 12.0],
})
items = pd.DataFrame({
"sku": [1, 2, 2],
"name": ["Pen", "Book", "Book"],
"qty": [3, 1, 2],
})
merged = products.merge(
items,
left_on="product_id",
right_on="sku",
suffixes=("_catalog", "_order"),
)
print(merged.columns.tolist())The printed list is ['product_id', 'name_catalog', 'price', 'sku', 'name_order', 'qty']. Two things happened:
- Both key columns,
product_idandsku, are in the result. When you merge withon, pandas keeps one key column because the two are identical by definition. Withleft_onandright_on, the names differ, so pandas keeps both. - Both tables have a non-key column called
name. pandas cannot keep two columns with the same label, sosuffixesrenames them. The next chapter covers suffixes in detail. For now, note that they apply only to overlapping non-key columns.
Once you have confirmed the two key columns hold the same values, you can drop the redundant one:
merged = merged.drop(columns="sku")If you prefer to avoid the redundant column, rename before merging. items.rename(columns={"sku": "product_id"}) lets you use on="product_id". Renaming is cleaner when you will reuse the renamed table. left_on and right_on are cleaner when you want to leave the source tables untouched.
Outer joins with differently named keys
With on, an outer join fills the single key column from whichever side has the row. With left_on and right_on, the two key columns stay separate. A row that exists only in the right table has NaN in the left key column. A row that exists only in the left table has NaN in the right key column. Integer keys that gain NaN become floats, which can surprise you later.
If you need one complete key column after an outer join, combine the two:
products = pd.DataFrame({"product_id": [1, 2, 3], "price": [1.5, 12.0, 4.0]})
items = pd.DataFrame({"sku": [1, 2, 4], "qty": [3, 1, 7]})
outer = products.merge(items, left_on="product_id", right_on="sku", how="outer")
outer["key"] = outer["product_id"].fillna(outer["sku"])
print(outer[["product_id", "sku", "key"]])The new key column holds 1, 2, 3, and 4 as floats. Convert it with .astype(int) if you need integers.
Multiple keys
Sometimes no single column identifies a row. A store has one row per month, so store repeats. A month has one row per store, so month repeats. Only the pair (store, month) is unique. Pass a list to on to match on the combination:
import pandas as pd
sales = pd.DataFrame({
"store": ["N", "N", "S", "S"],
"month": ["2026-01", "2026-02", "2026-01", "2026-02"],
"revenue": [100, 120, 90, 95],
})
targets = pd.DataFrame({
"store": ["N", "S", "S"],
"month": ["2026-01", "2026-01", "2026-02"],
"target": [110, 100, 90],
})
both = sales.merge(targets, on=["store", "month"])
print(both)The output is:
store month revenue target
0 N 2026-01 100 110
1 S 2026-01 90 100
2 S 2026-02 95 90A row from sales matches a row from targets only when every key column is equal. The row for store N in February has no target, so the default inner join drops it. Use how="left" to keep it, with NaN in target.
Using too few keys multiplies rows
Merging on only part of a composite key is a common mistake. Pandas does not warn you, because the merge is valid. Every pair of rows sharing the same store is matched:
partial = sales.merge(targets, on="store")
print(len(partial))
print(partial.columns.tolist())This prints 6, then ['store', 'month_x', 'revenue', 'month_y', 'target']. Store N has 2 sales rows and 1 target row, giving 2 rows. Store S has 2 sales rows and 2 target rows, giving 4. Because month is no longer a key, it overlaps, and pandas applies the default suffixes _x and _y. Seeing _x and _y columns in a result is a good hint that you left out a key.
Combining multiple keys with different names
left_on and right_on also accept lists. The lists are matched by position: the first name in left_on pairs with the first name in right_on, and so on.
targets_renamed = targets.rename(columns={"store": "shop", "month": "period"})
result = sales.merge(
targets_renamed,
left_on=["store", "month"],
right_on=["shop", "period"],
)
print(result.columns.tolist())The columns are ['store', 'month', 'revenue', 'shop', 'period', 'target']. The order of the two lists matters. Writing right_on=["period", "shop"] would compare store to period, which finds no matches and returns an empty result without raising an error.
You can also mix one key that differs in name with one that does not by listing both in left_on and right_on, repeating the shared name on each side. There is no way to combine on with left_on in one call.
Keys that live in the index
left_on and right_on can also name an index level instead of a column, as long as the level has a name. You can combine a column on one side with the index on the other using left_on="col", right_index=True. The next chapters cover index-based joins fully, including DataFrame.join.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError` naming a column | The name in `on`, `left_on`, or `right_on` is misspelled, or sits on the wrong side | Check `df.columns` for each table, including stray spaces |
| `MergeError` about `on` | `on` was passed together with `left_on` or `right_on` | Use only one style |
| `ValueError` about list length | `left_on` and `right_on` have different numbers of names | Give each side the same number of keys |
| `ValueError` about merging `int64` and `object` columns | Keys have incompatible dtypes, such as numbers stored as text | Convert one side with `astype` before merging |
| More rows than expected, with `_x` and `_y` columns | A key was left out, so rows were matched too broadly | Add the missing key column |
| Fewer rows than expected | Key values differ in case, whitespace, or type | Normalize keys before merging |
Dtype and text problems are covered in a later chapter. Row counts for duplicated keys are covered in the cardinality chapter.
Summary of the argument choices
- Use
onwhen the key columns share names. Pass a list for several keys. - Use
left_onandright_onwhen the names differ. Both key columns appear in the result, so drop the redundant one afterward. - Match all the columns that together identify a row. Omitting one multiplies rows.
- Keep both lists the same length and in the same order.
- With outer joins and differently named keys, expect
NaNin the key columns and combine them withfillnaif needed.
Exercise
A DataFrame left has columns city, year, and sales. A DataFrame right has columns town, yr, and population. A row should match only when the city equals the town and the year equals yr. Write the merge, keeping every row of left, and remove the redundant key columns from the result.
Show answer
left.merge(right, left_on=["city", "year"], right_on=["town", "yr"], how="left").drop(columns=["town", "yr"]). The lists pair city with town and year with yr by position. how="left" keeps every row of left, with NaN in population where no match exists. Both town and yr appear in the merged result, so drop removes them.
Exercise
You merge sales and targets on store alone and get 6 rows with columns month_x and month_y, although you expected 3 rows. What went wrong, and what is the fix?
Show answer
store does not identify a row, because each store appears once per month. Every sales row for a store is paired with every target row for that store, which multiplies the rows. The overlapping month column then gets the suffixes _x and _y. The fix is to merge on both columns: sales.merge(targets, on=["store", "month"]).