w3resource

Reset index of MultiIndex DataFrame in Pandas


6. Reset Index of a MultiIndex DataFrame

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to reset the index of a MultiIndex DataFrame to convert it back into columns.
  • Write a Pandas program to remove the MultiIndex from a DataFrame and then rename the new default index.
  • Write a Pandas program to reset the index of a MultiIndex DataFrame and then drop the old index levels.
  • Write a Pandas program to create a MultiIndex DataFrame, reset its index, and then sort the resulting DataFrame by a specific column.

Go to:


PREV : Swap Levels of a MultiIndex DataFrame.
NEXT : Indexing with .loc.

Python-Pandas Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.