Sub topic 6
Common rename pitfalls
This chapter covers the mistakes that most often break rename() calls. Most of them fail silently, so the code runs and the labels are wrong. It assumes you can build a DataFrame, select columns by label, and use dictionaries. It also assumes you know the rename() forms from earlier chapters: columns={"old": "new"} and columns=function.
Why rename() fails quietly
By default, rename() is forgiving. It returns a new DataFrame, ignores keys that match nothing, and does not check whether the new labels collide. That design is convenient for messy data. It also means a typo produces no error.
The table lists the pitfalls covered below and the symptom of each.
| Pitfall | Symptom | Fix |
|---|---|---|
| Result not assigned | Labels never change | `df = df.rename(...)` |
| `inplace=True` used with assignment | `df` becomes `None` | Avoid `inplace` |
| Key does not match a label | Column keeps its old name | `errors="raise"` |
| Mapping given without `columns=` | Row index changes instead | Name the axis |
| Two columns get the same name | `df["a"]` returns a DataFrame | Check `columns.is_unique` |
| Mapping written backwards | Nothing changes | Write `{old: new}` |
Pitfall 1: forgetting to assign the result
rename() does not change the DataFrame it is called on. It returns a modified copy. If you discard the copy, nothing changes.
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2], "Total $": [10.0, 20.0]})
df.rename(columns={"Order ID": "order_id"})
print(df.columns.tolist()) # ['Order ID', 'Total $']
df = df.rename(columns={"Order ID": "order_id"})
print(df.columns.tolist()) # ['order_id', 'Total $']The first call builds a renamed DataFrame and throws it away. Only the assigned version updates df.
Pitfall 2: inplace=True
rename() accepts inplace=True, which modifies the original object and returns None. This causes two problems.
First, people combine it with assignment. The assignment then replaces the DataFrame with None:
import pandas as pd
df = pd.DataFrame({"order_id": [1, 2], "total": [10.0, 20.0]})
result = df.rename(columns={"order_id": "id"}, inplace=True)
print(result) # None
print(df.columns.tolist()) # ['id', 'total']If you had written df = df.rename(..., inplace=True), every later use of df would fail with an AttributeError on None.
Second, inplace=True does not save memory in most cases, and it breaks method chaining because there is no return value to chain from. The pandas project discourages it. Use the assigned form unless you have a specific reason not to.
Pitfall 3: keys that match nothing are ignored
When a key in the mapping is not an existing label, rename() skips it without a message. Trailing spaces, different capitalization, and typos all cause this.
import pandas as pd
df = pd.DataFrame({"Customer Name ": ["Ann"], "total": [1]})
renamed = df.rename(columns={"Customer Name": "customer"})
print(renamed.columns.tolist()) # ['Customer Name ', 'total']The source label is "Customer Name " with a trailing space, so the key "Customer Name" matches nothing. The call succeeds and the column keeps its old name.
Pass errors="raise" to turn this into a KeyError:
import pandas as pd
df = pd.DataFrame({"Customer Name ": ["Ann"], "total": [1]})
try:
df.rename(columns={"Customer Name": "customer"}, errors="raise")
except KeyError as exc:
print("KeyError:", exc)Two details matter here:
- The check is all-or-nothing. If any key is missing, the call raises, even when other keys match.
- Labels are compared exactly.
"Total"and"total"are different keys.
Use errors="raise" in scripts and pipelines where the mapping is a contract with the data source. Keep the default "ignore" when the same mapping is applied to files that may or may not contain every column.
Pitfall 4: renaming the index by accident
rename() works on both axes. When you pass a mapping as the first positional argument without saying which axis, pandas applies it to the row index.
import pandas as pd
df = pd.DataFrame({"a": [1, 2]}, index=["a", "b"])
by_default = df.rename({"a": "x"})
print(by_default.columns.tolist()) # ['a']
print(by_default.index.tolist()) # ['x', 'b']
on_columns = df.rename({"a": "x"}, axis="columns")
print(on_columns.columns.tolist()) # ['x']In the first call the column "a" is untouched and the index label "a" became "x". Because unmatched keys are ignored, a wrong axis often produces no error at all. The quickest protection is to always write columns=, which names the axis in the call itself. axis="columns" and axis=1 do the same job.
Pitfall 5: the mapping runs the wrong way
The mapping direction is {old_label: new_label}. Writing it as {new: old} is easy to do, especially when you copy names from documentation. Since the "new" names are not present yet, nothing matches, and the default errors="ignore" hides the mistake.
import pandas as pd
df = pd.DataFrame({"Order ID": [1]})
backwards = df.rename(columns={"order_id": "Order ID"})
print(backwards.columns.tolist()) # ['Order ID']Again, errors="raise" finds this immediately. A habit that also helps is to read the mapping aloud as "rename Order ID to order_id".
Pitfall 6: renaming into a collision
rename() does not check whether the new labels are unique. If you rename a column to a name that already exists, you get two columns with the same label.
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2]})
clash = df.rename(columns={"b": "a"})
print(clash.columns.tolist()) # ['a', 'a']
print(clash.columns.is_unique) # False
print(type(clash["a"]).__name__) # DataFrameSelecting clash["a"] now returns a DataFrame with both columns, not a Series. Code that expects a Series, such as arithmetic or .str methods, then fails or behaves differently. Bulk cleaning can cause this without you intending it. For example, "Total $" and "Total %" both become "total" after a regular expression removes the symbols.
Make uniqueness part of the check after any rename:
import pandas as pd
df = pd.DataFrame({"Total $": [10.0], "Total %": [0.2]})
cleaned = df.rename(columns=lambda c: c.split()[0].lower())
if not cleaned.columns.is_unique:
dupes = cleaned.columns[cleaned.columns.duplicated()].tolist()
print("Collision:", dupes) # Collision: ['total']The fix is a mapping that gives the columns distinct names, such as {"Total $": "total_amount", "Total %": "total_rate"}. A later chapter covers how to handle duplicate labels that already exist.
A safer rename helper
You can combine the protections in one small function. It names the axis, raises on missing keys, and checks for collisions.
import pandas as pd
def rename_columns(df: pd.DataFrame, mapping: dict) -> pd.DataFrame:
out = df.rename(columns=mapping, errors="raise")
if not out.columns.is_unique:
dupes = out.columns[out.columns.duplicated()].unique().tolist()
raise ValueError(f"Rename created duplicate labels: {dupes}")
return out
df = pd.DataFrame({"Order ID": [1], "Total $": [10.0]})
df = rename_columns(df, {"Order ID": "order_id", "Total $": "total"})
print(df.columns.tolist()) # ['order_id', 'total']The function does not hide the pitfalls. It makes them fail loudly, which is what you want in a data pipeline.
Checking your work
After any rename, run three quick checks:
- Print
df.columns.tolist()and compare it to what you expect. - Confirm
df.columns.is_uniqueisTrue. - Confirm the shape did not change: renaming never adds or removes rows or columns.
Exercise
A colleague writes df.rename(columns={"Customer": "customer"}, inplace=True) and then df = df.rename(columns={"Total": "total"}, inplace=True). The first line works. After the second line, df.head() raises an AttributeError. Explain why, and rewrite both lines so that typos in either key raise an error.
Show answer
With inplace=True, rename() modifies the DataFrame and returns None. The second line assigns that None to df, so df.head() fails on None. Rewrite with a single assigned call and errors="raise": df = df.rename(columns={"Customer": "customer", "Total": "total"}, errors="raise"). If either key does not match a label, a KeyError is raised.
Exercise
Given df = pd.DataFrame({"x": [1], "y": [2]}, index=["y", "z"]), what does df.rename({"y": "w"}).columns.tolist() return, and why? Which argument fixes the call so that column "y" is renamed?
Show answer
It returns ['x', 'y']. A mapping without an axis applies to the row index, so index label "y" becomes "w" and the columns are unchanged. Use df.rename(columns={"y": "w"}) or df.rename({"y": "w"}, axis="columns").