ADVERTISEMENT
ADVERTISEMENT

How to flatten a hierarchical index in columns?

Learn how to flatten a hierarchical index in columns?
Submitted by Pranit Sharma, on May 06, 2022

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. Pandas allows us to achieve this task by using the reset_index() method.

pandas.DataFrame.reset_index() method

This method is used to rearrange or reset the hierarchical indices that occurred due to groupby aggregated functions.

Syntax:

DataFrame.reset_index(
    level=None, 
    drop=False, 
    inplace=False, 
    col_level=0, 
    col_fill=''
    )

Parameter(s):

  • 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:

# Importing pandas package
import pandas as pd

# Creating a Dictionary
dict = {
    'Name':['Amit','Bhairav','Chirag','Divyansh','Esha'],
    'Age':[20,20,19,21,18],
    'ID_No':[30,40,50,60,70]
}

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

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

# 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)

Output:

flatten a hierarchical index

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.