Turn Pandas Multi-Index into column
Last Updated :
22 Dec, 2023
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method.
DataFrame.reset_index() is used to reset the index to default and make the index a column of the DataFrame.
Turn Multi-Index into Column in Pandas
Below are the steps by which we can convert columns from multi-index in Pandas in Python:
Step 1: Creating a Multi-Index DataFrame
Let’s see an example by making a multi-index dataframe first. In this step, a multi-index DataFrame df
is created with tuples (‘A’, ‘a’), (‘A’, ‘b’), (‘B’, ‘a’), and (‘B’, ‘b’) as indices, and corresponding values 2, 4, 6, and 8.
Python3
tuples = [( 'A' , 'a' ), ( 'A' , 'b' ), ( 'B' , 'a' ), ( 'B' , 'b' )]
index = pd.MultiIndex.from_tuples(tuples, names = [ 'index_1' , 'index_2' ])
data = [ 2 , 4 , 6 , 8 ]
df = pd.DataFrame(data = data, index = index, columns = [ 'value' ])
print (df)
|
Output:
DataFrame created with multi-index
Step 2: Converting Index into the Column
Here we can see the hierarchical indexing, we are converting each index into a separate column using the reset_index() method.
Python3
new_df = df.reset_index()
print (new_df)
|
Output:
DataFrame after using reset_index() method
Here we can see that the all the levels of index are converted to columns. We can also select which level of multi-index to reset using parameter level.
level parameter can be an index name or can be a tuple or list of indices to remove from the dataframe and make them as dataframe columns.
Python3
new_df_2 = df.reset_index(level = ( "index_2" ,))
new_df_2.head()
|
Output:
DataFrame after using reset_index with level parameter set.
Note: Here, we can see that only “index_2” is reset from index and has become a column, but not “index_1“.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...