Sub topic 4
Merging on Differently Named and Multiple Keys
This chapter assumes you can create DataFrames, know what the index is, and have run a basic merge with on= and a how= join type. Here you will match columns that have different names, match on several columns at once, and handle the shared column names that result.
When the key names differ
Real tables rarely agree on column names. One table calls the key product_id and another calls it sku. Use left_on for the column in the left DataFrame and right_on for the column in the right one.
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 output is:
['product_id', 'name_catalog', 'price', 'sku', 'name_order', 'qty']Two things to notice. First, both key columns, product_id and sku, stay in the result. With on=, pandas keeps a single key column. With left_on and right_on, it keeps both, because they are different columns. Drop the one you do not need with merged.drop(columns="sku").
Second, both tables had a name column that was not a key. pandas cannot keep two columns with the same name, so it renames them using suffixes. Without the argument, the defaults are _x and _y, which tell you nothing about where each column came from. Pass descriptive suffixes.
Matching on multiple keys
Sometimes one column does not identify a row. A store's daily sales are identified by store and date together. Pass a list to on to require all the columns to match.
sales = pd.DataFrame({
"store": ["N", "N", "S"],
"date": ["2026-01-01", "2026-01-02", "2026-01-01"],
"units": [5, 7, 3],
})
targets = pd.DataFrame({
"store": ["N", "N", "S"],
"date": ["2026-01-01", "2026-01-02", "2026-01-01"],
"target": [6, 6, 4],
})
both = sales.merge(targets, on=["store", "date"])
print(both)A row matches only when store and date are both equal. Merging on store alone would pair every sale at store N with every target at store N, producing four rows for N instead of two.
You can combine the two ideas by passing lists of equal length to left_on and right_on. The columns pair up by position: the first left column matches the first right column, and so on.
result = sales.merge(
targets.rename(columns={"store": "shop", "date": "day"}),
left_on=["store", "date"],
right_on=["shop", "day"],
)Common errors
- Using
onwith a name that exists in only one table. This raises aKeyError. Useleft_onandright_oninstead. - Mixing
onwithleft_onorright_on. pandas does not allow both in the same call. - Lists of different lengths.
left_on=["a", "b"]withright_on=["c"]fails, because the keys cannot pair up. - Forgetting the leftover key column. After a
left_on/right_onmerge, you get both key columns. In an outer join, one of them isNaNfor rows that had no match.
Exercise
You merge orders (key column cust) with customers (key column customer_id) using orders.merge(customers, left_on="cust", right_on="customer_id"). How many key columns does the result contain, and why?
Show answer
Two, cust and customer_id. When the key names differ, pandas treats them as separate columns and keeps both. Only on= merges the key into one column. Drop the extra one with drop(columns=...) if you do not need it.
Exercise
Two tables both have region and year columns, and each combination of region and year appears once per table. Write the merge call that matches rows on both columns.
Show answer
left.merge(right, on=["region", "year"]). A row matches only when both values are equal.