Open In App

Reverting from Multi-Index to Single Index DataFrame in Pandas

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Let’s learn how to revert a multi-index to a single index DataFrame in Pandas.

Setting Up a Multi-Index DataFrame in Pandas

To begin, let’s import Pandas and load the data (data.csv):

Output:

Data

At this point, the DataFrame doesn’t have any specific index, but we can create a multi-index using the set_index() method. We’ll use the ‘region’, ‘state’, and ‘individuals’ columns as index levels:

Output:

Multi-Index-DataFrame

Multi-Index Pandas DataFrame

Now, the DataFrame has a hierarchical index, commonly referred to as a multi-index.

Reverting from Multi-Index to Single Index using reset_index()

Pandas offers several ways to reset a multi-index, depending on your needs. The reset_index() method can be used in different ways to drop or retain certain index levels.

Method 1: Reverting Using Index Levels

You can specify the index levels you want to remove using the level parameter. In this case, we will remove ‘region’ (level 0) and ‘individuals’ (level 2), keeping ‘state’ (level 1) as the single index.

Output:

Method-1

DataFrame with Single Index

Method 2: Reverting Using Index Names

Alternatively, you can specify the index names directly in a list to reset them. Here, we will reset the ‘region’ and ‘state’ indexes, leaving ‘individuals’ as the index:

Output:

Method-2

Method 3: Removing All Indexes

If you want to completely remove the index from your DataFrame (i.e., convert it to an index-free DataFrame), you can pass all the index names to the reset_index() function:

Output:

Method-3

Convert MultiIndex to Single Index using droplevel() Method

To drop one of the index levels, use the droplevel() method. In this example, we remove the ‘number’ level while keeping the ‘letter’ level.

Output:

Multi-Index-DataFrame-to-Single-Index-using-droplevel


Practice Tags :

Similar Reads