Rename DataFrame rows and columns in Pandas

Python

Pandas

DataFrame

Rename rows and columns

Papa D.

Python

Pandas

DataFrame

When working with Pandas DataFrames, long column and row names lead to excessive typing and messy code. By renaming the rows and columns, DataFrames can be much easier to use.

Code Example

Use the DataFrame.rename() method to rename rows or columns.

import pandas as pd

# Create a DataFrame with bad column names
penguins = pd.DataFrame({
    'first_name': ['Tim', 'Midge', 'Ronald', 'Amy'], 
    'the_food_they_like_the_most': ['fish', 'fish', 'fish', 'fingers'],
    'years_spent_living': [2, 18, 12, 8],
    'can_fly': [False, False, True, False]
})

# Change the column names here
penguins = penguins.rename(columns={
    'first_name': 'name',
    'the_food_they_like_the_most': 'favorite_food',
    'years_spent_living': 'age',
})
penguins
name favorite_food age can_fly
0 Tim fish 2 False
1 Midge fish 18 False
2 Ronald fish 12 True
3 Amy fingers 8 False

More Examples

Rename Row Labels

named_rows_penguins = penguins.set_index('name')

named_rows_penguins.rename(index={
    'Tim': 'Slim',
    'Midge': 'May',
    'Ronald': 'Clown',
    'Amy': 'Danger',
})
favorite_food age can_fly
name
Slim fish 2 False
May fish 18 False
Clown fish 12 True
Danger fingers 8 False