Recipe: How to rename multiple column headers in a Pandas DataFrame?
DATA MUNGING PYTHON PANDAS DATAFRAME PANDAS CHEATSHEET PANDAS DATAFRAME TUTORIAL PANDAS COLUMN

How to rename multiple column headers in a Pandas DataFrame?

This recipe helps you rename multiple column headers in a Pandas DataFrame
In [1]:
## How to rename multiple column headers in a Pandas DataFrame
def Snippet_103():
    print()
    print(format('How to rename multiple column headers in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Set ipython's max row display
    pd.set_option('display.max_row', 1000)

    # Set iPython's max column width to 50
    pd.set_option('display.max_columns', 50)

    # Create an example dataframe
    data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
            'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08',
                     '2012, 02, 08', '2012, 02, 08'],
            'Score': [4, 24, 31, 2, 3]}
    df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz',
                                     'Maricopa', 'Yuma'])
    print(); print(df)

    # Rename Column Names
    df.columns = ['Leader', 'Time', 'Score']
    print(); print(df)

    # Rename Column Name Leader to Commander
    df.rename(columns={'Leader':'Commander'}, inplace=True)
    print(); print(df)

Snippet_103()
***********How to rename multiple column headers in a Pandas DataFrame************

           Commander          Date  Score
Cochice        Jason  2012, 02, 08      4
Pima           Molly  2012, 02, 08     24
Santa Cruz      Tina  2012, 02, 08     31
Maricopa        Jake  2012, 02, 08      2
Yuma             Amy  2012, 02, 08      3

           Leader          Time  Score
Cochice     Jason  2012, 02, 08      4
Pima        Molly  2012, 02, 08     24
Santa Cruz   Tina  2012, 02, 08     31
Maricopa     Jake  2012, 02, 08      2
Yuma          Amy  2012, 02, 08      3

           Commander          Time  Score
Cochice        Jason  2012, 02, 08      4
Pima           Molly  2012, 02, 08     24
Santa Cruz      Tina  2012, 02, 08     31
Maricopa        Jake  2012, 02, 08      2
Yuma             Amy  2012, 02, 08      3


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from Emids
1 developer from ICU Medical
1 developer from Vodafone
1 developer from Altimetrik
1 developer from Ericsson
1 developer from MThree
1 developer from ANAC
1 developer from HCL
1 developer from Renovite Technologies
1 developer from eClerx