w3resource

Reset index of MultiIndex DataFrame in Pandas

Pandas: Advanced Indexing and Slicing Exercise-6 with Solution

Reset Index:

Write a Pandas program to reset the index of a MultiIndex DataFrame.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'A': [1, 6, 8, 3, 7],
    'B': [5, 2, 9, 4, 1],
    'C': ['one', 'one', 'two', 'two', 'one']
})

# Set MultiIndex
df = df.set_index(['C', 'A'])

# Reset the index
df = df.reset_index()
print(df)

Output:

     C  A  B
0  one  1  5
1  one  6  2
2  two  8  9
3  two  3  4
4  one  7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Set a MultiIndex using columns 'C' and 'A'.
  • Reset the index to default.
  • Print the DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Swap MultiIndex Levels in Pandas DataFrame.
Next: Indexing with .loc in Pandas DataFrame.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/reset-index-of-multiindex-dataframe-in-pandas.php