Sub topic 5
Handling overlapping columns with suffixes
This chapter assumes you can create DataFrames, select columns, and run a basic merge with on= and left_on=/right_on=. You should also know the default inner join. Here you will learn what happens when both tables have a non-key column with the same name, and how to control the result.
The problem: the same name in both tables
A merge returns one table. A DataFrame cannot hold two columns with the same label without confusion, so pandas must rename one or both.
By default, pandas appends _x to the left column and _y to the right column. These names say nothing about the data.
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())The output is:
['product_id', 'name_x', 'price', 'sku', 'name_y', 'qty']The price and qty columns appear in only one table, so they keep their names. Only name is in both, so it becomes name_x and name_y.
Naming the suffixes
The suffixes parameter takes a tuple of two strings. The first goes on the left table's overlapping columns. The second goes on the right table's.
merged = products.merge(
items,
left_on="product_id",
right_on="sku",
suffixes=("_catalog", "_order"),
)
print(merged.columns.tolist())Now the columns are name_catalog and name_order, and the origin of each is clear.
Rules that cause surprises
- Key columns are not suffixed when you use
on=. If both tables usecustomer_idand you passon="customer_id", pandas produces onecustomer_idcolumn. - Keys with
left_onandright_onare kept separately. In the example above, bothproduct_idandskuappear. Drop one afterward if you do not need it. - Suffixes apply only to overlapping names. Columns that appear in one table keep their original labels.
- Use
Noneto leave one side unchanged. For example,suffixes=(None, "_order")keepsnamefrom the left table and renames the right one toname_order. - Empty suffixes on both sides raise an error. If both are
Noneor empty, the merge would produce duplicate labels, and pandas raises aValueError.
Checking whether the columns agree
Overlapping columns often hold the same information, such as a name stored in both tables. After the merge, compare them to find disagreements.
merged["name_matches"] = merged["name_catalog"] == merged["name_order"]
print(merged[["product_id", "name_catalog", "name_order", "name_matches"]])If every row matches, drop one column:
clean = merged.drop(columns=["name_order", "sku"]).rename(
columns={"name_catalog": "name"}
)
print(clean.columns.tolist())If some rows differ, you have found a data quality problem that you should investigate before dropping anything.
Avoiding the overlap
You can also avoid overlap before merging. Select only the columns you need from the right table:
slim = items[["sku", "qty"]]
result = products.merge(slim, left_on="product_id", right_on="sku")
print(result.columns.tolist())The result has no name_x or name_y, because name now exists only in products. This is often the cleanest approach when the overlapping column is redundant.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Columns named `_x` and `_y` | No `suffixes` given | Pass descriptive suffixes |
| `KeyError: 'name'` after merge | The column was renamed by suffixes | Use the suffixed name, such as `name_catalog` |
| `ValueError` about duplicate columns | Both suffixes are empty or `None` | Give at least one side a suffix |
| Two key columns remain | Used `left_on` and `right_on` | Drop the extra key column |
Exercise
You merge orders and shipments on order_id. Both tables have a status column. You want to keep both, labeled status_order and status_shipment. Write the merge call.
Show answer
orders.merge(shipments, on="orderid", suffixes=("order", "shipment")). The left table's status becomes statusorder and the right table's becomes statusshipment. The key orderid is not suffixed because it is passed to on=.
Exercise
A merge with left_on="product_id", right_on="sku" gives a result with both product_id and sku. Why, and how do you remove the duplicate?
Show answer
The key columns have different names, so pandas keeps both. Remove one with result.drop(columns="sku").