The Pandas MultiIndex function to_frame() used to convert a DataFrame with the levels of the MultiIndex as columns. It returns a DataFrame object that includes the MultiIndex data.
1 MultiIndex.to_frame(index = True, name = _NoDefault.no_default, allow_duplicates = False)
index : It is boolean value that sets the index to the resulting DataFrame as the original MultiIndex.
name : It can be either list or sequence of string that substitute index level with names.
allow_duplicates : It is boolean that specifies whether to allows duplicate column labels to the created DataFrame. If not specified, the default value will be False.
1 import pandas as pd
2
3 mIndex = pd.MultiIndex.from_tuples([[1, 2],[3, 4]])
4
5 print('The MultiIndex object :')
6 print(mIndex)
7
8 res = mIndex.to_frame()
9 print('The converted DataFrame object :')
10 print(res)
In the above example, a MultiIndex object is created by using from_tuples() function by passing an array of arrays. A to_frame() function is called that converts a DataFrame object by keeping Index of MultiIndex data. The result is assign to a variable that will be printed on console.
1 The MultiIndex object :
2 MultiIndex([(1, 2),
3 (3, 4)],
4 )
5 The converted DataFrame object :
6 0 1
7 1 2 1 2
8 3 4 3 4
to_frame() with index as False
to_frame() with index as False
1 import pandas as pd
2
3 mIndex = pd.MultiIndex.from_tuples([[1, 2],[3, 4]])
4
5 print('The MultiIndex object :')
6 print(mIndex)
7
8 res = mIndex.to_frame(index = False)
9 print('The converted DataFrame object :')
10 print(res)
In the above example, a to_frame() function is called by passing index as False that converts a DataFrame object that includes the default index.
1 The MultiIndex object :
2 MultiIndex([(1, 2),
3 (3, 4)],
4 )
5 The converted DataFrame object :
6 0 1
7 0 1 2
8 1 3 4
to_frame() with index as False and name
to_frame() with index as False and name
1 import pandas as pd
2
3 mIndex = pd.MultiIndex.from_tuples([[1, 2],[3, 4]])
4
5 print('The MultiIndex object :')
6 print(mIndex)
7
8 res = mIndex.to_frame(index = False, name = ['C1', 'C2'])
9 print('The converted DataFrame object :')
10 print(res)
In the above example, a to_frame() function is called by passing index as False and name that converts a DataFrame object that includes the default index and name that specifies the columns for the DataFrame.
1 The MultiIndex object :
2 MultiIndex([(1, 2),
3 (3, 4)],
4 )
5 The converted DataFrame object :
6 C1 C2
7 0 1 2
8 1 3 4
Related options for your search