0
0
Pandasdata~5 mins

Renaming columns in Pandas

Choose your learning style9 modes available
Introduction

Renaming columns helps you give clear and meaningful names to your data. It makes your data easier to understand and work with.

When the original column names are unclear or too long.
When you want to standardize column names before analysis.
When merging data from different sources with different column names.
When preparing data for reports or presentations.
When fixing typos or inconsistent naming in column headers.
Syntax
Pandas
df.rename(columns={'old_name1': 'new_name1', 'old_name2': 'new_name2'}, inplace=True)

The columns parameter takes a dictionary mapping old names to new names.

Use inplace=True to change the DataFrame directly, or omit it to get a new DataFrame.

Examples
This changes column 'A' to 'Age' and 'B' to 'Height' in the same DataFrame.
Pandas
df.rename(columns={'A': 'Age', 'B': 'Height'}, inplace=True)
This creates a new DataFrame with renamed columns, leaving the original unchanged.
Pandas
new_df = df.rename(columns={'old': 'new'})
This renames all columns to uppercase using a function.
Pandas
df.rename(columns=lambda x: x.upper(), inplace=True)
Sample Program

This program creates a simple table with columns 'Name', 'Age', and 'City'. Then it renames 'Name' to 'First Name' and 'City' to 'Location'.

Pandas
import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30], 'City': ['NY', 'LA']}
df = pd.DataFrame(data)

print('Before renaming:')
print(df)

# Rename columns
rename_dict = {'Name': 'First Name', 'City': 'Location'}
df.rename(columns=rename_dict, inplace=True)

print('\nAfter renaming:')
print(df)
OutputSuccess
Important Notes

If you rename columns without inplace=True, remember to assign the result to a new variable.

You can rename one or many columns at once by adding more pairs in the dictionary.

Summary

Renaming columns makes your data easier to read and use.

Use a dictionary to map old names to new names.

Choose inplace=True to rename directly or create a new DataFrame.