Title: Rename Column Headers In Pandas
Slug: pandas_rename_column_headers
Summary: Rename Column Headers In Pandas
Date: 2016-06-17 12:00
Category: Python
Tags: Data Wrangling Authors: Chris Albon

Originally from rgalbo on StackOverflow.

Preliminaries


In [34]:
# Import required modules
import pandas as pd

Create example data


In [35]:
# 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
df


Out[35]:
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

Replace the header value with the first row's values


In [36]:
# Create a new variable called 'header' from the first row of the dataset
header = df.iloc[0]


Out[36]:
0      first_name
1       last_name
2             age
3    preTestScore
Name: 0, dtype: object

In [37]:
# Replace the dataframe with a new one which does not contain the first row
df = df[1:]

In [38]:
# Rename the dataframe's column values with the header variable
df.rename(columns = header)


Out[38]:
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