Lesson 13 · Mastering Pandas
How to Rename Columns and Indexes in pandas DataFrames for Clear Data Analysis
Learning to rename columns and indexes helps make your data easier to understand and work with. We will use the Titanic Dataset for this lesson. Let us…
- CourseMastering Pandas
- Lesson13 of 44
- Video17 min
- FormatJupyter notebook · 15 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbRenaming Columns and Indexes in Pandas#
Learning to rename columns and indexes helps make your data easier to understand and work with.
We will use the Titanic Dataset for this lesson.
Let us explore how and why to rename columns and indexes.
import warnings; warnings.filterwarnings('ignore')
# Data setup (Titanic Dataset)
import pandas as pd
import numpy as np
np.random.seed(42)
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
Why Rename Columns or Indexes?#
- Column names may be long, unclear, or have typos
- You may want to match column names across datasets
- Clean names make analysis easier
print(df.columns)
Basic Renaming with rename()#
To rename columns or index values, use the .rename() method.
You provide a mapping: the current name, and the new name you want.
# Rename 'Sex' column to 'Gender' and 'Pclass' to 'PassengerClass'
df_renamed = df.rename(columns={ 'Sex': 'Gender', 'Pclass': 'PassengerClass' })
print(df_renamed.columns[:7])
# The original DataFrame is unchanged unless inplace=True
print('Sex' in df.columns)
print('Gender' in df.columns)
# Rename in place to update the DataFrame itself
df.rename(columns={ 'Sex': 'Gender', 'Pclass': 'PassengerClass' }, inplace=True)
print(df.columns[:7])
# Rename multiple columns: abbreviate Age and update Embarked
df.rename(columns={'Age': 'A', 'Embarked': 'PortOfEmbarkation'}, inplace=True)
print(df.columns[:7])
Renaming Columns with str Methods#
When columns have patterns such as extra spaces, uppercase letters, or special characters, use string methods.
For example, you can make all columns lowercase or strip whitespace.
Let us see this in action.
# Make all columns lowercase and remove spaces
df.columns = df.columns.str.lower().str.replace(' ', '', regex=False)
print(df.columns[:7])
# Replace underscores with spaces and capitalize words
df.columns = df.columns.str.replace('_', ' ').str.title()
print(df.columns[:7])
Renaming the DataFrame Index#
To rename DataFrame row indexes, use the rename() method with the index argument.
This is helpful when your index is not just numbers, for example after grouping.
# Example: set 'PassengerId' as index, then rename some index values
df_indexed = df.set_index('Passengerid')
df_indexed = df_indexed.rename(index={1: 'FirstPassenger', 2: 'SecondPassenger'})
print(df_indexed.head(3))
# Reset index to go back to default numbering
df_reset = df_indexed.reset_index()
print(df_reset.head(2))
Common Pitfall: inplace vs Not inplace#
- Using
inplace=Truedirectly edits your DataFrame and you cannot undo - Without
inplace=True, your original stays unchanged unless you save the result
Use caution: decide if you want to keep the changes or not.
# Quick practice: Rename 'Fare' to 'TicketPrice' using input()
current = input('Type the current column name you want to rename: ')
new = input('Type the new name: ')
df2 = df.rename(columns={current: new})
print(df2.columns)
# SCENARIO: Standardize all column names to lower case and no spaces
cols_standard = df.columns.str.lower().str.replace(' ', '', regex=False)
print(cols_standard)
# Undo column name changes by restoring from original data
df_restore = pd.read_csv(url)
print(df_restore.columns)
Use Case: Renaming Before Merging#
When combining datasets, names must match exactly.
Renaming ahead of merging helps ensure the join works right.
# Mini-challenge: Rename all columns to be snake_case
df_snake = df.copy()
df_snake.columns = df_snake.columns.str.lower().str.replace(' ', '_').str.replace('__', '_')
print(df_snake.columns[:7])
# Quick tip: Rename all columns using a list
columns_new = [f'feature_{i}' for i in range(len(df.columns))]
df.columns = columns_new
print(df.head(2))
Practice and Apply#
- Make all column names lower case.
- Remove all spaces, replace with underscores.
- Try renaming 'Survived' to 'Outcome'.
These steps will help you solidify your new skills!
Recap: Renaming Columns and Indexes#
- Use
.rename()for specific changes, use string methods for patterns - Always check your results after renaming
- Clean names save time and reduce mistakes
- Practice and you will master tidy DataFrames!
Thank you for learning with us!#
For more Python and pandas lessons, subscribe and click the bell.
See you in the next video!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



