rename

Rename is used to change the names of labels on an axis. Most of the time I use this to rename columns. I'm going to use the titanic dataset from seaborn to illustrate. Here's my raw data.


import pandas as pd
import seaborn as sns

df = sns.load_dataset('titanic')
df.head(5)
          
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True

Rename dataframe columns

The main thing that I use this function for is to rename the columns of a pandas dataframe. Pass in a dictionary as the columns parameter, where the keys are the names of the columns before, and the values are the names of the columns after.


(
    df
    .rename(columns={
        'pclass': 'passenger_class',
        'sibsp': 'siblings_onboard',
        'parch': 'parents_children_onboard'
    })
).head(5)
          
survived passenger_class sex age siblings_onboard parents_children_onboard fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True