0
0
Pandasdata~5 mins

Resetting MultiIndex to columns in Pandas

Choose your learning style9 modes available
Introduction

Sometimes data has multiple index levels that make it hard to work with. Resetting MultiIndex moves these index levels back into normal columns so you can use them easily.

You want to convert grouped data back to a regular table.
You need to save or export data without complex indexes.
You want to perform operations that require columns instead of indexes.
You want to merge or join dataframes using index values as columns.
Syntax
Pandas
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')

level lets you choose which index levels to reset. If None, all levels reset.

drop=True removes the index levels instead of moving them to columns.

Examples
Reset all index levels to columns, creating a default integer index.
Pandas
df.reset_index()
Reset only the 'year' level of the MultiIndex to a column.
Pandas
df.reset_index(level='year')
Remove all index levels without adding them as columns.
Pandas
df.reset_index(drop=True)
Sample Program

This code creates a DataFrame with a MultiIndex of year and month. Then it resets the index so year and month become normal columns.

Pandas
import pandas as pd

# Create a sample MultiIndex DataFrame
data = {"sales": [100, 200, 150, 300]}
index = pd.MultiIndex.from_tuples(
    [(2023, "Jan"), (2023, "Feb"), (2024, "Jan"), (2024, "Feb")],
    names=["year", "month"]
)
df = pd.DataFrame(data, index=index)

print("Original DataFrame with MultiIndex:")
print(df)

# Reset the MultiIndex to columns
reset_df = df.reset_index()

print("\nDataFrame after resetting MultiIndex to columns:")
print(reset_df)
OutputSuccess
Important Notes

Resetting index creates a new DataFrame by default. Use inplace=True to modify the original.

If you only want to remove the index without keeping it as columns, use drop=True.

Summary

Resetting MultiIndex moves index levels back to columns for easier use.

You can reset all or specific index levels.

Use drop=True to remove index levels without adding columns.