How to add header row to a Pandas DataFrame?

Given a Pandas DataFrame, we have to add header row. By Pranit Sharma Last updated : September 21, 2023

Pandas is a special tool which allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structure in pandas. DataFrames consists of rows, columns and the data.

Columns are the different fields which contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Each column has specific header/name.

Problem statement

Given a Pandas DataFrame, we have to add header row.

Adding header row to a Pandas DataFrame

We can add a header row by simply assigning a list of names that we want to give as the header in front of DataFrame.columns =.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example.

Python program to add header row to a Pandas DataFrame

Step 1: Create and print the dataframe

# Importing pandas package
import pandas as pd

# Crerating an array
arr1 = ['Sachin', 15921, 18426]
arr2 = ['Ganguly', 7212, 11363]
arr3 = ['Dravid', 13228, 10889]
arr4 = ['Yuvraj', 1900, 8701]
arr5 = ['Dhoni', 4876, 10773]
arr6 = ['Kohli', 8043, 12311]

final_arr = [arr1,arr2,arr3,arr4,arr5,arr6]

# Creating a DataFrame
df = pd.DataFrame(final_arr)

# Display created DataFrame
print("Created DataFrame:\n",df,"\n")

Output:

Example 1: Add header row to a DataFrame

Step 2: Add a row of headers to classify DataFrame

Now, add a row of headers to classify our DataFrame.

# Adding column headers
df.columns = ['Players','Test_runs','ODI_runs']

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Example 2: Add header row to a DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.