How to flatten a hierarchical index in columns?

Learn how to flatten a hierarchical index in columns? By Pranit Sharma Last updated : September 19, 2023

While creating structured grouped data in pandas, we use the hierarchical indexing method. These hierarchical indexes are useful for complex data queries. Here, we are going to learn how to flatten these hierarchical indices in columns.

Flatten a hierarchical index in columns

Pandas allows us to achieve this task by using the reset_index() method. This method is used to rearrange or reset the hierarchical indices that occurred due to groupby aggregated functions.




  • It takes a parameter called level, if defined then removes the particular levels from the indices.
  • It takes another parameter called drop, which is defined to set the flatten index to the default integer index.
  • Also, it takes a parameter called inplace which modifies the original DataFrame without creating a copy.

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 flatten a hierarchical index in columns

# Importing pandas package
import pandas as pd

# Creating a Dictionary
dict = {

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

# Display DataFrame

# Using groupby on Name based on sum of age
result = df.groupby(by='Name').agg(sum)

# Display Result
print("Grouped data\n",result,"\n")

# Reset index
reset = result.reset_index()

# Display reset
print("Reset indices\n",reset)


The output of the above program is:

flatten a hierarchical index

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.