close

How to simply add a column level to a pandas dataframe

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to simply add a column level to a pandas dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to simply add a column level to a pandas dataframe?

  1. How to simply add a column level to a pandas dataframe?

    A solution which adds a name to the new level and is easier on the eyes than other answers already presented:

  2. simply add a column level to a pandas dataframe

    A solution which adds a name to the new level and is easier on the eyes than other answers already presented:

Method 1

df.columns = pd.MultiIndex.from_product([df.columns, ['C']])

print(df)
#    A  B
#    C  C
# a  0  0
# b  1  1
# c  2  2
# d  3  3
# e  4  4

Method 2

A solution which adds a name to the new level and is easier on the eyes than other answers already presented:

df['newlevel'] = 'C'
df = df.set_index('newlevel', append=True).unstack('newlevel')

print(df)
#           A  B
# newlevel  C  C
# a         0  0
# b         1  1
# c         2  2
# d         3  3
# e         4  4

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read