rename()'s columns and index parameters each take a dict mapping existing labels to new ones — only the labels you explicitly mention get changed, and any label not present as a key in the dict is left exactly as it was. This targeted approach is usually more convenient than reassigning the whole df.columns list directly, especially when you only need to fix one or two column names rather than relabel every single one.
1Understanding df.rename()
rename()'s columns and index parameters each take a dict mapping existing labels to new ones — only the labels you explicitly mention get changed, and any label not present as a key in the dict is left exactly as it was. This targeted approach is usually more convenient than reassigning the whole df.columns list directly, especially when you only need to fix one or two column names rather than relabel every single one.
By default, rename() returns a new DataFrame and leaves the original unchanged — pass inplace=True if you specifically want to modify the DataFrame directly instead of capturing rename()'s return value in a new variable.
import pandas as pd
df = pd.DataFrame({"Name": ["Alice"], "Age": [30]})
df = df.rename(columns={"Name": "name", "Age": "age"})
print(df.columns.tolist())2Practical Example
Here is a real-world application of df.rename() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"First Name": ["Alice"], "Last Name": ["Smith"]})
df = df.rename(columns=str.lower)
print(df.columns.tolist())3Best Practices
Follow these guidelines when working with df.rename():
1. Use rename(columns={'old': 'new'}) for targeted renaming of specific columns, rather than reassigning the entire df.columns list
2. Remember rename() returns a new DataFrame by default — either capture its return value or pass inplace=True to modify the original directly
3. Use a function instead of a dict for columns, like a lowercasing function, when you need to apply the same transformation to every column name at once
Tip: By default, rename() returns a new DataFrame and leaves the original unchanged — pass inplace=True if you specifically want to modify the DataFrame directly instead of capturing rename()'s return value in a new variable.
import pandas as pd
df = pd.DataFrame({"Name": ["Alice"], "Age": [30]})
df = df.rename(columns={"Name": "name", "Age": "age"})
print(df.columns.tolist())