Sub topic 3
Renaming every column with a function
This chapter assumes you can build a DataFrame, pass a dictionary to rename(), and call basic string methods such as strip and lower. A dictionary works well when you rename a few columns. If every label needs the same fix, a function is shorter and cannot miss a column.
How rename() uses a function
rename(columns=...) accepts a callable as well as a dictionary. pandas calls the function once for each column label. The return value becomes the new label. As with the dictionary form, the result is a new DataFrame, so you must assign it.
Passing an existing function
Any function that takes one label and returns one label will work. A built-in string method is the simplest choice.
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)Pass the function itself (str.lower), not a call (str.lower()). The second half of the example shows the errors option, which applies to dictionary mappings. A function is applied to every label, so there are no unmatched keys to report.
Combining several steps with a lambda
When one string method is not enough, write a lambda. This example strips stray spaces, lowercases, and replaces inner spaces with underscores.
import pandas as pd
df = pd.DataFrame({" Order ID": [1], "Customer Name ": ["Ann"]})
cleaned = df.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
print(cleaned.columns.tolist()) # ['order_id', 'customer_name']If the logic grows past one line, define a named function with def. It is easier to test and to reuse on other DataFrames.
Common errors
- Non-string labels. Column labels can be integers or other types.
str.lowerfails on an integer label, and a lambda that calls.strip()fails the same way. Convert withstr()first. - Forgetting to assign.
df.rename(columns=str.lower)on its own leavesdfunchanged. Writedf = df.rename(...). - Two labels becoming one. If
"ID"and"id"both pass throughstr.lower, you get two columns namedid. pandas allows this without any warning. Check the result, as covered in the later chapter on duplicate column labels.
import pandas as pd
df = pd.DataFrame([[1, 2]], columns=[2024, "Total"])
# df.rename(columns=str.lower) raises TypeError because 2024 is an int.
safe = df.rename(columns=lambda c: str(c).lower())
print(safe.columns.tolist()) # ['2024', 'total']Function or dictionary?
| Situation | Better choice |
|---|---|
| Change one or two named columns | Dictionary |
| Apply the same rule to all columns | Function |
| Fix a few columns and apply a rule to the rest | Function first, then a dictionary |
Chaining the two calls keeps each step easy to read.
Exercise
A DataFrame has the columns [" Unit Price", "QTY ", 2025]. Write one rename() call that returns lowercase, stripped labels with spaces replaced by underscores, without raising an error. What is the resulting list of labels?
Show answer
Use df.rename(columns=lambda c: str(c).strip().lower().replace(" ", "")). The str() call handles the integer label 2025. The result is ['unitprice', 'qty', '2025'].