Rename Column Headers In Pandas

Originally from rgalbo on StackOverflow.

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

Preliminaries

# Import required modules
import pandas as pd

Create example data

# 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
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

# Create a new variable called 'header' from the first row of the dataset
header = df.iloc[0]
0      first_name
1       last_name
2             age
3    preTestScore
Name: 0, dtype: object
# Replace the dataframe with a new one which does not contain the first row
df = df[1:]
# Rename the dataframe's column values with the header variable
df.rename(columns = header)
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