Sub topic 3
Renaming every column with a function
This chapter covers passing a function to rename() so that pandas rewrites every column label in one step. It assumes you can build a DataFrame, call df.rename(columns={...}) with a dictionary, and write a short Python function that uses string methods such as strip and lower.
Why use a function instead of a dictionary
A dictionary mapping lists each old label and its new label. That works for three or four columns, but it is tedious for fifty. It also fails quietly when a new column shows up with a label you didn't list.
A function expresses a rule instead: "lowercase every label" or "replace spaces with underscores". The rule covers every column, including ones added later.
rename() accepts a function wherever it accepts a mapping. pandas calls the function once per label, passes the label as the only argument, and uses the return value as the new label.
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2]})
lowered = df.rename(columns=str.lower)
print(lowered.columns.tolist()) # ['a', 'b']
# Unmatched keys are ignored by default; errors="raise" makes them fail.
try:
df.rename(columns={"missing": "x"}, errors="raise")
except KeyError as exc:
print("KeyError:", exc)The first call passes the unbound method str.lower. pandas calls str.lower("A") and str.lower("B"). Don't write str.lower() with parentheses, because that calls the function immediately and passes its result instead.
The second call shows a contrast with dictionaries. A key that matches no column is ignored by default, and errors="raise" turns that into a KeyError. A function has no keys that could fail to match, so this problem does not apply to it.
How the call flows
The data is not copied cell by cell into a different structure. Only the label index changes. The original df keeps its old labels, so you must assign the result to a name to keep it.
Writing your own function
Built-in methods such as str.lower, str.upper, and str.title are fine for one-step rules. For anything else, define a function. A named function is easier to test than a long lambda.
import pandas as pd
def to_snake(label):
return label.strip().lower().replace(" ", "_")
df = pd.DataFrame({
" Order ID": [1],
"Customer Name ": ["Ann"],
"Total": [10.0],
})
renamed = df.rename(columns=to_snake)
print(renamed.columns.tolist()) # ['order_id', 'customer_name', 'total']The function trims whitespace first, then lowercases, then swaps spaces for underscores. The order matters. If you replaced spaces before stripping, the leading space in " Order ID" would become a leading underscore.
You can also test the function without any DataFrame: to_snake(" Order ID") returns 'order_id'. This is a real advantage over a .str chain on df.columns, which you can only run against a live DataFrame.
Rules that apply to only some columns
The function receives every label, so it has to return something for every label. To change only some columns, return the label unchanged for the rest.
import pandas as pd
df = pd.DataFrame({"x_a": [1], "x_b": [2], "id": [3]})
renamed = df.rename(columns=lambda c: c.removeprefix("x_"))
print(renamed.columns.tolist()) # ['a', 'b', 'id']removeprefix already returns the original string when the prefix is missing, so id passes through unchanged. When your rule lacks that behavior, write an explicit conditional: lambda c: c.upper() if c.startswith("x_") else c. A function that returns None for unmatched labels would give those columns the label None, which is almost never what you want.
removeprefix needs Python 3.9 or later.
Non-string labels
Column labels are not always strings. Reading a file with no header gives integer labels, and a pivot table can produce dates or numbers. A string method applied to an integer raises an error.
import pandas as pd
df = pd.DataFrame([[1, 2, 3]], columns=[2024, "Region", "Total"])
try:
df.rename(columns=str.lower)
except TypeError as exc:
print("TypeError:", type(exc).__name__) # TypeError: TypeError
safe = df.rename(columns=lambda c: str(c).lower())
print(safe.columns.tolist()) # ['2024', 'region', 'total']Converting with str(c) makes the function safe for any label type. The cost is that 2024 becomes the string "2024". Code that later selects df[2024] will then fail, so decide whether you want that conversion before applying it everywhere.
Collisions: two labels become one
A function can map different labels to the same result. pandas does not stop you.
import pandas as pd
df = pd.DataFrame([[1, 2]], columns=["Total", "total"])
renamed = df.rename(columns=str.lower)
print(renamed.columns.tolist()) # ['total', 'total']
print(renamed.columns.is_unique) # FalseNo error is raised, and the DataFrame now has two columns named total. Selecting renamed["total"] returns a two-column DataFrame instead of a Series, which breaks code that expects one column. Check is_unique after any bulk rename. A later chapter covers how to handle duplicate labels once they exist.
Other axes and equivalent forms
rename() works on row labels as well. The columns= keyword targets column labels and the index= keyword targets row labels. You can pass a function to either.
| Call | What it changes |
|---|---|
| `df.rename(columns=str.lower)` | Column labels |
| `df.rename(index=str.title)` | Row labels |
| `df.rename(str.lower, axis="columns")` | Column labels, with the function passed positionally |
| `df.add_prefix("raw_")` | Every column label, by adding a prefix |
| `df.add_suffix("_v2")` | Every column label, by adding a suffix |
For a plain prefix or suffix, add_prefix and add_suffix are shorter and communicate the intent better than a lambda.
When the columns are a MultiIndex (labels with several levels), a function passed to rename() runs on each label at every level. The level argument limits the change to one level: df.rename(columns=str.lower, level=0).
Common mistakes
- Forgetting to assign.
df.rename(columns=str.lower)on its own prints a result in a notebook but leavesdfunchanged in a script. Writedf = df.rename(...). - Using
inplace=True. It still works, but the pandas documentation discourages it, and it does not save memory in most cases. Assignment is clearer and works in method chains. - Calling the function.
columns=str.lower()raises aTypeErrorbecausestr.lowerneeds an argument. Pass the function, not its result. - Returning a non-label. If the function returns a list or a Series, pandas raises an error or builds a broken label. Return one hashable value, normally a string.
- Ignoring side effects in the function. pandas does not promise an order of calls beyond one call per label. Keep the function free of counters and other state.
Summary
df.rename(columns=func)callsfuncon every column label and returns a new DataFrame.- Pass the function itself, not a call to it.
- Convert with
str(c)when labels might not be strings. - Return unmatched labels unchanged when you want a partial rename.
- A function can create duplicate labels without an error, so check
df.columns.is_uniqueafterward.
Exercise
A DataFrame has the columns ["Unit Price", "unit price", "Qty"]. You run df = df.rename(columns=lambda c: c.lower().replace(" ", "_")). What are the new column labels, and what problem does the result have? How would you detect it in code?
Show answer
The new labels are ['unit_price', 'unit_price', 'qty']. The first two labels collapse into the same name, so the DataFrame has duplicate column labels, and df["unit_price"] returns a two-column DataFrame instead of one Series. pandas raises no error. Detect it with df.columns.is_unique, which returns False, or with df.columns.duplicated().any(), which returns True.
Exercise
A DataFrame has the columns [2023, "Sales", "Region"]. Write a single rename() call that lowercases every label without raising an error. What type are the resulting labels?
Show answer
df.rename(columns=lambda c: str(c).lower()). Calling str.lower directly fails with a TypeError on the integer label 2023. The lambda converts each label to a string first, so the result is ['2023', 'sales', 'region'], and every label, including the former integer, is now a string.