Sub topic 6
Common rename pitfalls
This chapter assumes you can build a DataFrame, pass a dictionary to rename(), and read df.columns. Most rename bugs fail silently, so you see no error and the labels simply stay the same.
Pitfall 1: forgetting that rename() returns a copy
rename() does not change the DataFrame it is called on. It returns a new one. If you don't assign the result, the original keeps its old labels.
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2], "Total $": [10.0, 20.0]})
df.rename(columns={"Order ID": "order_id"}) # result thrown away
print(df.columns.tolist()) # ['Order ID', 'Total $']
df = df.rename(columns={"Order ID": "order_id"})
print(df.columns.tolist()) # ['order_id', 'Total $']Pitfall 2: inplace=True and the None trap
inplace=True modifies the DataFrame and returns None. Combining it with assignment replaces your DataFrame with None.
import pandas as pd
df = pd.DataFrame({"A": [1]})
df = df.rename(columns={"A": "a"}, inplace=True)
print(df) # NonePrefer df = df.rename(...). It works in method chains, and you can't get this bug.
Pitfall 3: unmatched keys are ignored
A key that matches no label does nothing, and pandas raises no error. Typos, different capitalization, and stray spaces are the usual causes.
import pandas as pd
df = pd.DataFrame({"Order ID": [1], " Total $": [10.0]})
renamed = df.rename(columns={"Total $": "total"}) # label has a leading space
print(renamed.columns.tolist()) # ['Order ID', ' Total $']
try:
df.rename(columns={"Total $": "total"}, errors="raise")
except KeyError:
print("KeyError: key did not match any column")Use errors="raise" in scripts and pipelines, where a missed rename should stop the run.
Pitfall 4: renaming the index instead of the columns
The first argument of rename() applies to the row index by default. Without columns=, your mapping targets the wrong axis.
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2]})
wrong = df.rename({"Order ID": "order_id"})
print(wrong.columns.tolist()) # ['Order ID']
right = df.rename(columns={"Order ID": "order_id"})
print(right.columns.tolist()) # ['order_id']Pitfall 5: renames that create duplicate labels
Nothing stops you from giving two columns the same name. This can happen when a cleanup rule collapses different labels into one.
import pandas as pd
df = pd.DataFrame([[1, 2]], columns=["Total $", "Total %"])
df = df.rename(columns={"Total $": "total", "Total %": "total"})
print(df.columns.tolist()) # ['total', 'total']
print(df.columns.is_unique) # FalseAfter this, df["total"] returns a DataFrame with two columns instead of a Series. Duplicate labels are covered in a later chapter.
A short check after every rename
Run a quick check right after renaming:
import pandas as pd
df = pd.DataFrame({"Order ID": [1], "Total $": [10.0]})
mapping = {"Order ID": "order_id", "Total $": "total"}
df = df.rename(columns=mapping, errors="raise")
assert df.columns.is_unique
assert set(mapping.values()) <= set(df.columns)
print(df.columns.tolist()) # ['order_id', 'total']The first assertion catches collisions. The second confirms every new name is present.
| Symptom | Likely cause | Fix |
|---|---|---|
| Labels unchanged | Result not assigned | `df = df.rename(...)` |
| `df` is `None` | Assigned the result of `inplace=True` | Drop `inplace` |
| Some labels unchanged | Key typo or whitespace | `errors="raise"`, inspect `df.columns` |
| Columns unchanged, no error | Missing `columns=` | Pass `columns={...}` |
| Duplicate names | Two keys map to one value | Check `df.columns.is_unique` |
Exercise
A colleague writes df = df.rename(columns={"Customer": "customer"}, inplace=True) and then df.head() raises an AttributeError. What went wrong, and how do you fix it? Also name one way to find out whether "Customer" matched a column.
Show answer
With inplace=True, rename() returns None, so df was reassigned to None, and None has no head(). Remove inplace=True and keep the assignment: df = df.rename(columns={"Customer": "customer"}). To check that the key matched, pass errors="raise" so a missing label raises a KeyError. You can also print df.columns.tolist() and look for stray spaces or different capitalization.