Sub topic 5
Handling overlapping columns with suffixes
This chapter assumes you can build DataFrames, select columns, read a merge result, and use merge with on, left_on, and right_on. Earlier chapters covered those. Here the question is what pandas does when both tables have a column with the same name and that column is not the one you join on.
What counts as an overlapping column
Two tables often share column names. Some of those are keys, such as customer_id. Others are ordinary data that happen to share a name, such as name, price, or updated_at.
- When you merge with
on="customer_id", the key appears once in the result. - When you merge with
left_onandright_onand the key names differ, both key columns stay in the result. - Any other column name present in both tables is an overlap. pandas cannot keep two columns with the same name side by side without ambiguity, so it renames both using suffixes.
The default suffixes are _x for the left table and _y for the right table.
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],
})
default = products.merge(items, left_on="product_id", right_on="sku")
print(default.columns.tolist())
# ['product_id', 'name_x', 'price', 'sku', 'name_y', 'qty']Only name is renamed. price and qty exist in one table each, so they keep their names. Suffixes apply to collisions only.
Choosing meaningful suffixes
_x and _y say nothing about where a value came from. Someone reading the result a month later has to work out which side was which. Set suffixes to a tuple of two strings, left first and right second.
merged = products.merge(
items,
left_on="product_id",
right_on="sku",
suffixes=("_catalog", "_order"),
)
print(merged.columns.tolist())
# ['product_id', 'name_catalog', 'price', 'sku', 'name_order', 'qty']Good suffixes describe the source of the data (_catalog, _order) or the period (_jan, _feb). Avoid _left and _right unless the table order carries meaning, because "left" changes whenever you swap the operands.
Keeping one side's original name
One suffix may be None. The column from that side keeps its original name, and the other side gets a suffix.
partial = products.merge(
items,
left_on="product_id",
right_on="sku",
suffixes=(None, "_order"),
)
print(partial.columns.tolist())
# ['product_id', 'name', 'price', 'sku', 'name_order', 'qty']This works well when one table is the main one and the other adds a few extra columns. If both suffixes are None and a column overlaps, pandas 2.0 and later raises ValueError. Older versions only warned.
Using suffixes to compare two versions of the same data
A common use is putting two snapshots of the same table side by side. Both have identical column names, so every non-key column overlaps. Suffixes turn that into a comparison.
jan = pd.DataFrame({"id": [1, 2, 3], "sales": [100, 200, 300]})
feb = pd.DataFrame({"id": [1, 2, 4], "sales": [110, 190, 50]})
change = jan.merge(feb, on="id", how="outer", suffixes=("_jan", "_feb"))
change["delta"] = change["sales_feb"] - change["sales_jan"]
print(change) id sales_jan sales_feb delta
0 1 100.0 110.0 10.0
1 2 200.0 190.0 -10.0
2 3 300.0 NaN NaN
3 4 NaN 50.0 NaNThe outer join keeps ids that exist in only one month. The missing side becomes NaN, which also turns the integer columns into floats. The delta is NaN for those rows, which is correct, because there is nothing to compare.
Deciding whether suffixes are the right fix
Suffixes keep both versions of a column. That is not always what you want. Work through the situation first.
The shared column is part of the key
Suppose customers and orders both have customer_id and region. If region describes the same fact in both tables, merging only on customer_id produces region_x and region_y, which are mostly identical. Adding region to the key list matches on both columns and keeps one copy.
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"region": ["EU", "US", "EU"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12],
"customer_id": [1, 2, 3],
"region": ["EU", "US", "US"],
})
by_id = customers.merge(orders, on="customer_id")
print(by_id.columns.tolist())
# ['customer_id', 'region_x', 'order_id', 'region_y']
by_both = customers.merge(orders, on=["customer_id", "region"])
print(len(by_id), len(by_both))
# 3 2Adding a column to on changes which rows match. Customer 3 is in EU in one table and US in the other, so the inner merge on both keys drops that row. This is the right choice only when the two values are supposed to agree. When they might disagree and you want to find those cases, keep the suffixes and compare region_x with region_y.
You only need one version
If one side's column is redundant, remove it before the merge. This avoids suffixes entirely and keeps the result small.
slim = products.merge(
items[["sku", "qty"]],
left_on="product_id",
right_on="sku",
).drop(columns="sku")
print(slim.columns.tolist())
# ['product_id', 'name', 'price', 'qty']Selecting the columns you need from each side is also the clearest way to document what the merge adds. It avoids pulling many unused columns into memory.
Overlaps with DataFrame.join
DataFrame.join is built on the same machinery as merge, but it names its suffix arguments differently and has no default suffixes. If the two frames share a non-key column and you give no suffix, join raises ValueError and reports the overlapping columns.
left = pd.DataFrame({"score": [1, 2]}, index=["a", "b"])
right = pd.DataFrame({"score": [10, 30]}, index=["a", "c"])
try:
left.join(right)
except ValueError as err:
print("join failed:", err)
print(left.join(right, lsuffix="_left", rsuffix="_right")) score_left score_right
a 1 10.0
b 2 NaNThe differences between the two interfaces are easy to mix up.
| Aspect | `merge` | `join` |
|---|---|---|
| Suffix argument | `suffixes=("_x", "_y")`, one tuple | `lsuffix` and `rsuffix`, two strings |
| Default when columns overlap | `_x` and `_y` | `ValueError` |
| Both suffixes empty | `ValueError` in pandas 2.0 and later | `ValueError` |
| Default join type | `inner` | `left` |
Note that left and right in the example above keep their original score columns. The renaming happens only in the returned frame.
Gotchas
Suffixes do not rename key columns you merge on
With on="id", the single id column in the result is not suffixed. With left_on and right_on, the two key columns have different names, so neither is renamed. The exception is when left_on and right_on are the same name on a column that is not otherwise merged. In that case you should use on instead.
Chained merges produce confusing names
Suffixes apply per merge call. Consider three tables that all have a status column.
- The first merge turns
statusintostatus_aandstatus_b. - The third table's
statusdoes not collide with either of those names. - The second merge therefore leaves it as a plain
status.
The result then has status_a, status_b, and status, and the plain name belongs to the newest table. Pass distinct suffixes at each step, or rename the column in each table before you start.
Suffixed names can collide with existing columns
If a frame already contains name_x, merging it with another frame that overlaps on name creates a second name_x. Rename first, and check the result with df.columns.is_unique.
Rename before merging for stable code
Renaming columns before the merge is more explicit than relying on suffixes, and it makes the data's origin clear at the point where it enters the pipeline.
items_renamed = items.rename(columns={"name": "ordered_name"})
clean = products.merge(items_renamed, left_on="product_id", right_on="sku")
print(clean.columns.tolist())
# ['product_id', 'name', 'price', 'sku', 'ordered_name', 'qty']Use suffixes for quick comparisons and one-off analysis. Use rename or column selection in code that others will maintain.
Exercise
You merge a = pd.DataFrame({"k": [1, 2], "v": [5, 6]}) with b = pd.DataFrame({"k": [1, 2], "v": [7, 8], "w": [0, 0]}) using a.merge(b, on="k", suffixes=("_a", None)). What are the result's column names, and what happens if you also pass None for the first suffix?
Show answer
The columns are ['k', 'v_a', 'v', 'w']. The left v gets the suffix _a and the right v keeps its name, while k and w are unaffected. With suffixes=(None, None), pandas 2.0 and later raises ValueError, because v overlaps and there is no way to tell the two columns apart.
Exercise
Two DataFrames old and new both have columns id and price. Write a merge that keeps every id from either table and adds a price_diff column showing the new price minus the old price. Which rows will have NaN in price_diff?
Show answer
Use both = old.merge(new, on="id", how="outer", suffixes=("_old", "_new")), then both["price_diff"] = both["price_new"] - both["price_old"]. The price_diff value is NaN for ids present in only one table, because the other price is missing.