Python | Pandas MultiIndex.to_frame()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.to_frame()
function create a DataFrame with the levels of the MultiIndex as columns.
Syntax: MultiIndex.to_frame(index=True)
Parameters :
index : Set the index of the returned DataFrame as the original MultiIndex.
Returns : DataFrame : a DataFrame containing the original MultiIndex data.
Example #1: Use MultiIndex.to_frame()
function to construct a dataframe using the MultiIndex levels as the column and index.
import pandas as pd
midx = pd.MultiIndex.from_tuples([( 10 , 'Ten' ), ( 10 , 'Twenty' ),
( 20 , 'Ten' ), ( 20 , 'Twenty' )],
names = [ 'Num' , 'Char' ])
print (midx)
|
Output :
Now let’s construct the dataframe from the MultiIndex.
midx.to_frame(index = True )
|
Output :
As we can see in the output, the function has constructed the Dataframe using the MultiIndex. Notice the index of the dataframe is constructed using the levels of the MultiIndex.
Example #2: Use MultiIndex.to_frame()
function to construct a DataFrame using the MultiIndex. Do not use the MultiIndex levels to construct the index of the Dataframe.
import pandas as pd
midx = pd.MultiIndex.from_tuples([( 10 , 'Ten' ), ( 10 , 'Twenty' ),
( 20 , 'Ten' ), ( 20 , 'Twenty' )],
names = [ 'Num' , 'Char' ])
print (midx)
|
Output :
Now let’s create a dataframe using the midx MultiIndex.
midx.to_frame(index = False )
|
Output :
As we can see in the output, the function has returned a DataFrame having different index value.
Last Updated :
24 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...