Renaming columns
Rename columns with a mapping, or replace all names at once by assigning a new list.
In this page:
Syntax
df = df.rename(columns={"old_name": "new_name"})
Renaming columns
rename(columns={"old": "new"}) changes selected labels and returns a new DataFrame. Assigning df.columns = [...] replaces all names and needs the exact number. String methods on df.columns, such as str.lower(), clean names in bulk.
Note:
df.columns.str.strip().str.lower() standardizes messy headers.
Example: Renaming columns
import pandas as pd
df = pd.DataFrame({" First Name ": ["Ann"], "AGE": [28]})
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
print(df.columns.tolist())
print(df.rename(columns={"age": "years"}))
# Output:
# ['first_name', 'age']
# first_name years
# 0 Ann 28
Related Topics
Common Mistakes
- Forgetting rename returns a copy
- Providing the wrong number of names
- Leaving stray spaces in headers
Chapter Summary
- rename with a dict changes some labels
- columns = [...] replaces all
- String methods clean headers in bulk
- rename returns a copy
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: