How to Rename Columns in Pandas โ With Examples
Answer
Use df.rename(columns={'old': 'new'}) to rename specific columns, or assign a new list directly to df.columns to rename all columns at once. Add inplace=True to modify the original dataframe, or reassign the result.
Why This Happens
Column names from raw data are often messy โ spaces, inconsistent casing, unclear abbreviations. Clean column names make your code more readable, prevent KeyErrors, and are required before merging dataframes with different naming conventions.
Solution
The rule: use .rename() for specific columns, direct assignment to .columns for bulk changes, and .str methods for cleaning patterns.
import pandas as pd
df = pd.DataFrame({'First Name': ['Alice', 'Bob'], 'Annual Salary': [50000, 60000]})
# โ
Rename specific columns with a dictionary
df = df.rename(columns={'First Name': 'first_name', 'Annual Salary': 'salary'})
# โ
Rename with inplace
df.rename(columns={'first_name': 'name'}, inplace=True)
# โ
Rename all columns at once
df.columns = ['name', 'salary']
# โ
Clean up column names (lowercase, replace spaces)
df.columns = df.columns.str.lower().str.replace(' ', '_')
# โ
Strip whitespace from column names
df.columns = df.columns.str.strip()
# โ
Add prefix or suffix to all columns
df = df.add_prefix('user_')
df = df.add_suffix('_2024')
# โ
Rename using a function
df = df.rename(columns=lambda x: x.lower().replace(' ', '_'))Better Workflow
Zerve persists your dataframe state at each cell, so you can experiment with different naming conventions and instantly see the result. If you don't like it, your previous version is still there โ no need to re-run your data loading.
)
&w=1200&q=75)
&w=1200&q=75)
&w=1200&q=75)