How to Use the First Row as the Header in Pandas

To use the first row as a header in Pandas we can:

(1) Convert first row to header - reset index

df.columns = df.iloc[0]
df = df[1:].reset_index(drop=True)

(2) Convert first row to header - keep index

headers = df.iloc[0].values
df.columns = headers
df.drop(index=0, axis=0, inplace=True)

(3) Read CSV with row 1 as header

pd.read_csv('filename.csv', header = 1)

or:

pd.read_csv('filename.csv', skiprows = 1)

Steps to Use the First Row as Header

Step 1: Create a DataFrame

Assume we have a DataFrame where the first row contains the actual column headers:

import pandas as pd

data = [
    ['id', 'name', 'age'],  # Row that should be the header
    [1, 'Alice', 25],
    [2, 'Bob', 30],
    [3, 'Charlie', 35]
]

df = pd.DataFrame(data)

dataframe looks like:

0 1 2
0 id name age
1 1 Alice 25
2 2 Bob 30
3 3 Charlie 35

Step 2: Convert First row as Header

We can use pd.DataFrame.iloc to extract the first row and assign it as the header:

df.columns = df.iloc[0]
df = df[1:].reset_index(drop=True)

result:

id name age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35

Step 3: First row to Header and keep index

We can use pd.DataFrame.iloc to extract the first row and assign it as the header:

headers = df.iloc[0].values
df.columns = headers
df = df.drop(index=0, axis=0)

result:

id name age
1 1 Alice 25
2 2 Bob 30
3 3 Charlie 35