JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Reverting from a multi-index to a single index in Pandas

Author:JIYIK Last Updated:2025/04/12 Views:

This tutorial teaches how to restore from a MultiIndex to a single index DataFrame in Pandas using Python.

MultiIndexDataFrame, also known as multi-level and hierarchical DataFrame, allows users to have multiple columns that can identify a row while each column index is related to each other through different parent-child relationships in the table.

We can use two methods to convert a multi-level index to a single-level index. We will learn the flexibility and higher efficiency of operating DataFrame in Pandas.


Rename columns to standard columns to convert MultiIndex to single index in Pandas

We have to first create a DataFrame consisting of MultiIndex columns in this method. After that, we can change the name of the columns, i.e. standard columns, so we can get rid of MultiIndex easily and without any errors.

Below is the code for the entire process following this approach from the beginning.

import pandas as pd
import numpy as np

# build an example DataFrame
midx = pd.MultiIndex(
    levels=[["zero", "one"], ["x", "y"]],
    codes=[
        [
            1,
            1,
            0,
        ],
        [
            1,
            0,
            1,
        ],
    ],
)
df = pd.DataFrame(np.random.randn(2, 3), columns=midx)
print(df)

This code will give us the following output.

        one                zero
          y         x         y
0  0.785806 -0.679039  0.513451
1 -0.337862 -0.350690 -1.423253

So, we can observe that a DataFrame has been created with a multi-level index column. To restore this column to a single-level index, we need to rename them in the method below.

df.columns = ["A", "B", "C"]
print(df)

The output of the above code is as follows.

          A         B         C
0  0.785806 -0.679039  0.513451
1 -0.337862 -0.350690 -1.423253

Hierarchical indexes have been removed and only the new names appear, replacing the old names of the columns.


Resetting the levels of columns in Pandas to convert MultiIndex to single index

In this approach, we simply reset the levels of the MultiIndex columns to convert them into single-level columns.

reset_index()Method allows the user to reset the index of a DataFrame and consider the default index again. One or more levels can be removed simultaneously using this method.

We will do this by adding a line to the code snippet we used previously. Let's consider a different example to learn the technique with more clarity and flexibility.

index = pd.MultiIndex.from_tuples(
    [("bird", "falcon"), ("bird", "parrot"), ("mammal", "lion"), ("mammal", "monkey")],
    names=["class", "name"],
)
columns = pd.MultiIndex.from_tuples([("speed", "max"), ("species", "type")])
df = pd.DataFrame(
    [(389.0, "fly"), (24.0, "fly"), (80.5, "run"), (np.nan, "jump")],
    index=index,
    columns=columns,
)
print(df)

The above code will give us the following output.

				speed	species
				max		type
class	name
bird	falcon	389.0	fly
		parrot	24.0	fly
mammal	lion	80.5	run
		monkey	NaN	    jump

We will use reset_index()the method to get the following output.

print(df.reset_index(level="class"))
		 class  speed species
                  max    type
name
falcon    bird  389.0     fly
parrot    bird   24.0     fly
lion    mammal   80.5     run
monkey  mammal    NaN    jump

reset_index()The method will reset the index of the columns by which the hierarchy levels are diluted and converted into a single-level column DataFrame. The output of the above code will be shown below.

Therefore, in this tutorial, we learned how to convert a MultiIndex column back to a single-level column without errors and easily without confusion.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Finding the installed version of Pandas

Publish Date:2025/04/12 Views:190 Category:Python

Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc

KeyError in Pandas

Publish Date:2025/04/12 Views:81 Category:Python

This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest

Grouping and Sorting in Pandas

Publish Date:2025/04/12 Views:90 Category:Python

This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies

Plotting Line Graph with Data Points in Pandas

Publish Date:2025/04/12 Views:65 Category:Python

Pandas is an open source data analysis library in Python. It provides many built-in methods to perform operations on numerical data. Data visualization is very popular nowadays and is used to quickly analyze data visually. We can visualize

Converting Timedelta to Int in Pandas

Publish Date:2025/04/12 Views:123 Category:Python

This tutorial will discuss converting a to a using dt the attribute in Pandas . timedelta int Use the Pandas dt attribute to timedelta convert int To timedelta convert to an integer value, we can use the property pandas of the library dt .

Pandas fill NaN values

Publish Date:2025/04/12 Views:93 Category:Python

This tutorial explains how we can use DataFrame.fillna() the method to fill NaN values ​​with specified values. We will use the following DataFrame in this article. import numpy as np import pandas as pd roll_no = [ 501 , 502 , 503 , 50

Pandas Convert String to Number

Publish Date:2025/04/12 Views:147 Category:Python

This tutorial explains how to pandas.to_numeric() convert string values ​​of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :

How to Change the Data Type of a Column in Pandas

Publish Date:2025/04/12 Views:139 Category:Python

We will look at methods for changing the data type of columns in a Pandas Dataframe, as well as options like to_numaric , , as_type and infer_objects . We will also discuss how to to_numaric use downcasting the option in . to_numeric Method

Get the first row of Dataframe Pandas

Publish Date:2025/04/12 Views:78 Category:Python

This tutorial explains how to use the get_first_row pandas.DataFrame.iloc attribute and pandas.DataFrame.head() get_first_row method from a Pandas DataFrame. We will use the following DataFrame in the following example to explain how to get

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial