Home »
Python »
Python Programs
How to add main column header for multiple column headings?
Given a Pandas DataFrame, we have to add main column header for multiple column headings.
Submitted by Pranit Sharma, on July 11, 2022
Pandas is a special tool that 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 structures in pandas. DataFrames consist of rows, columns, and data.
Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Each column has a specific header/name.
The header is nothing but it is a title or heading of columns that represent the name of the column.
Problem statement
Given a Pandas DataFrame, we have to add main column header for multiple column headings.
Add main column header for multiple column headings
To add a main column header for multiple column headings, these types of operations are useful when we have some fields and their particular subfields. The fields and subfields can share a relationship of parent and child, if there are two-child and one parent, the desired output will represent the parent column in between the two-child columns.
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 main column header for multiple column headings
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'Name': ['Shahruk','Salman','Amir','Saif Ali'],
'Movies':['DDLJ','Sultan','Dangal','Phantom'],
'Year':[1995,2016,2016,2015],
'Collection':['200 cr','623 cr','716 cr','84 cr']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Giving more columns
df.columns = [['A','A','B','B'],['Name','Movies','Year','Collection']]
# Display modified DataFrame
print('Modified DataFriend:\n',df)
Output
Python Pandas Programs »