How to prepend a level to a pandas MultiIndex?

Given a Pandas MultiIndex, we have to prepend a level in it. By Pranit Sharma Last updated : September 22, 2023

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.

Multilevel indexing is a type of indexing that include different levels of indexes or simply multiple indexes. The DataFrame is classified under multiple indexes and the topmost index layer is presented as level 0 of the multilevel index followed by level 1, level 2, and so on.

Problem statement

Given a Pandas MultiIndex, we have to prepend a level in it.

Prepending a level to a pandas MultiIndex

For this purpose, we will use pandas.concat() method which is used to add any column or value in DataFrame based on the specified object passed inside the method. Here, we will pass our whole DataFrame as a value along with a key which we want to make a level for multi-index purpose.

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 prepend a level to a pandas MultiIndex

# Importing pandas package
import pandas as pd

# Creating a dictionary
d= {'Country':['India','China','Sri-Lanka','Japan']}

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

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

# Prepend a level named as firstlevel
print(pd.concat({'Asia': df}, names=['Firstlevel']))

Output

The output of the above program is:

Example: Prepend a level to a pandas MultiIndex

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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