How to RENAME Column Header in a Pandas DataFrame in Python

January 17, 2019

Contact Seller

Guest Post Description

How to RENAME Column Header in a Pandas DataFrame in Python

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 in a Pandas DataFrame in Python

Add a Review

You must be logged in to post a comment.