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.
In [34]:
# Import required modules
import pandas as pd
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]:
In [36]:
# Create a new variable called 'header' from the first row of the dataset
header = df.iloc[0]
Out[36]:
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]: