Renaming Columns
Let me show you how to rename columns in your DataFrame. Sometimes the data you load has messy column names, and you need to clean them up.
Rename Specific Columns
Use the `rename()` method with a dictionary mapping old names to new names:
import pandas as pd
data = {'First Name': ['Alice', 'Bob'],
'Last Name': ['Smith', 'Jones'],
'Age (years)': [25, 30]}
df = pd.DataFrame(data)
df = df.rename(columns={'First Name': 'first_name',
'Last Name': 'last_name'})
print(df)
The dictionary maps old names to new ones. Notice I'm only renaming two columns — the third stays the same. This is the targeted approach.
Rename All Columns at Once
If you want to rename everything, assign directly to `columns`:
df.columns = ['first_name', 'last_name', 'age']
print(df)
This replaces all column names at once. Just make sure you get the order right.
Bulk Cleanup with str.replace
Here is the thing — when your column names have consistent patterns (like spaces or special characters), use string methods:
df.columns = df.columns.str.replace(' ', '_').str.lower()
print(df)
This replaces spaces with underscores and converts everything to lowercase. Super handy for cleaning up messy column names in one line.
Try it Yourself →Key Takeaways
- `rename()` with a dictionary renames specific columns
- Assign to `df.columns` to rename all columns at once
- `str.replace()` cleans up patterns across all column names
- Always assign back to `df` unless you use `inplace=True`