Open In App

How to add header row to a Pandas Dataframe?

Last Updated : 18 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Pandas, the header row defines column names for easy data access and manipulation. If your file lacks headers or you want to replace them, you can easily add custom headers using simple methods.

Let’s explore the most efficient ways to do this.

Using read_csv()

When you're reading a CSV or TXT file that doesn't have a header row, this is the most efficient way to assign column names. Just pass a list of column names using the names parameter during reading.

Python
import pandas as pd

df = pd.read_csv("data.txt", sep="\t", names=["Name", "Age", "Profession"])
print(df.columns.tolist())

Output

['Name', 'Age', 'Profession']

Explanation:

  • pd.read_csv("data.txt", ...) reads the file.
  • sep="\t" uses tab as the column separator.
  • names=[...] assigns custom column names (no header in file).
  • df.columns.tolist() outputs the column names as a list.

Using df.colums

If you've already read the file but want to add or change the column names, just assign a list of names to df.columns.

Python
import pandas as pd

df = pd.read_csv("data.txt", sep="\t", header=None)
df.columns = ["Name", "Age", "Profession"]
print(df.head())

Output

      Name  Age Profession 
0 Alice 30 Engineer
1 Bob 25 Designer
2 Charlie 28 Doctor

Explanation:

  • header=None tells Pandas there's no header in the file.
  • df.columns = [...] sets custom column names.
  • df.head() displays the first few rows.

Using set_axis()

It allows you to assign new column names while keeping your code clean and elegant. Just remember to reassign the result, unless you're using inplace=True.

Python
import pandas as pd

df = pd.read_csv("data.txt", header=None)
df.set_axis(["Name", "Age", "Profession"], axis=1)
print(df)

Output

      Name  Age Profession 
0 Alice 30 Engineer
1 Bob 25 Designer
2 Charlie 28 Doctor

Explanation:

  • set_axis([...], axis=1) sets new column names.
  • df = ... reassigns the result, unless using inplace=True.

Using rename()

Use rename() when you want to change only specific column names. It’s ideal for partial renaming, especially when dealing with numeric indices or maintaining backward compatibility with existing code.

Python
import pandas as pd

df = pd.read_csv("data.txt", header=None)
df = df.rename(columns={0: "Name", 1: "Age", 2: "Profession"})
print(df.columns)

Output

Index(['Name'], dtype='object')

Explanation:

  • columns={...} only renames the specified columns.
  • Other columns remain unchanged (still numeric labels here).

Related articles


Similar Reads