Python - Set MultiIndex of an existing DataFrame in pandas

Learn, how can we set multiindex for an existing DataFrame in Python pandas? By Pranit Sharma Last updated : September 29, 2023

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.

Multilevel indexing

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.

Set MultiIndex of an existing DataFrame

To set multiindex for an existing DataFrame in pandas, we will set the index of DataFrame to those column lists which we want to set as multiindex.

Let us understand with the help of an example,

Python program to set MultiIndex of an existing DataFrame in pandas

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'Name':['Pranit','Varun','Prajakta','Anushka'],
    'Age':[21,18,29,20],
    'College':['JNU','DU','BHU','IIT-B']
}

# Creating DataFrames
df = pd.DataFrame(d1)

# Display the DataFrames
print("Original DataFrame 1:\n",df,"\n\n")

# Setting index for this Dataframe
set_index = df.set_index(['Name', 'College'], inplace=True)

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

Output

The output of the above program is:

Example: Set MultiIndex of an existing DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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