
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements