Recipe: How to rename column header of a Pandas DataFrame?
DATA MUNGING PYTHON PANDAS DATAFRAME PANDAS CHEATSHEET PANDAS DATAFRAME TUTORIAL PANDAS COLUMN

How to rename column header of a Pandas DataFrame?

This recipe helps you rename column header of a Pandas DataFrame
In [1]:
## How to rename column header of a Pandas DataFrame
def Snippet_102():
    print()
    print(format('How to rename column header of a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create a values as dictionary of lists
    raw_data = {'0': ['first_name', 'Molly', 'Tina', 'Jake', 'Amy'],
                '1': ['last_name', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
                '2': ['age', 52, 36, 24, 73],
                '3': ['preTestScore', 24, 31, 2, 3]}

    # Create a dataframe
    df = pd.DataFrame(raw_data)

    # View a dataframe
    print(); print(df)

    # Create a new variable called 'header' from the first row of the dataset
    header = df.iloc[0]
    print(); print(header)

    # Replace the dataframe with a new one which does not contain the first row
    df = df[1:]
    print(); print(df)

    # Rename the dataframe's column values with the header variable
    df = df.rename(columns = header)
    print(); print(df)

Snippet_102()
****************How to rename column header of a Pandas DataFrame*****************

            0          1    2             3
0  first_name  last_name  age  preTestScore
1       Molly   Jacobson   52            24
2        Tina        Ali   36            31
3        Jake     Milner   24             2
4         Amy      Cooze   73             3

0      first_name
1       last_name
2             age
3    preTestScore
Name: 0, dtype: object

       0         1   2   3
1  Molly  Jacobson  52  24
2   Tina       Ali  36  31
3   Jake    Milner  24   2
4    Amy     Cooze  73   3

  first_name last_name age preTestScore
1      Molly  Jacobson  52           24
2       Tina       Ali  36           31
3       Jake    Milner  24            2
4        Amy     Cooze  73            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 eClerx
1 developer from Infosys
1 developer from Renovite Technologies
1 developer from Altimetrik
1 developer from Ericsson
1 developer from Karvy Stock Broking
1 developer from Tata Consultancy Services
1 developer from ANAC
1 developer from HvH
1 developer from Nokia