How to reset hierarchical index in Pandas?


To reset hierarchical index in Pandas, we can use reset_index() method.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Use groupby to get different levels of a hierarchical index and count it.

  • Print multi-hierarchical index DataFrame.

  • Reset the multi-hierarchical index DataFrame, using df.reset_index().

  • Print the new updated DataFrame.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame({"x": [5, 2, 1, 9], "y": [4, 1, 5, 10]})
print "Input DataFrame is:
", df df1 = df.groupby(["x", "y"]).count() print "Hierarchical Index of input DataFrame is:
", df1 df2 = df1.reset_index() print "After resetting:
", df2

Output

Input DataFrame is:
   x   y
0  5   4
1  2   1
2  1   5
3  9  10
Hierarchical Index of input DataFrame is:
Empty DataFrame
Columns: []
Index: [(1, 5), (2, 1), (5, 4), (9, 10)]
After resetting:
   x   y
0  1   5
1  2   1
2  5   4
3  9  10

Updated on: 30-Aug-2021

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements