Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns and substitute index level names

PythonServer Side ProgrammingProgramming

To create a DataFrame with the levels of the MultiIndex as columns, use the MultiIndex.to_frame() method. Substitute index level names using the name parameter.

At first, import the required libraries −

import pandas as pd

MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −

arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −

multiIndex = pd.MultiIndex.from_arrays(arrays)

Create a DataFrame with the levels of the MultiIndex as columns using to_frame(). Use the "name" parameter and pass the names to substitute index level names −

dataFrame = multiIndex.to_frame(name=['One', 'Two'])

Example

Following is the code −

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays)

# display the MultiIndex
print("The Multi-index...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
# Use the "name" parameter and pass the names to substitute index level names
dataFrame = multiIndex.to_frame(name=['One', 'Two'])

# Display the DataFrame
print("\nThe DataFrame...\n",dataFrame)

Output

This will produce the following output −

The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris')],
)

The levels in Multi-index...
[[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]

The DataFrame...
        One   Two
1  John  1   John
2  Tim   2    Tim
3  Jacob 3  Jacob
4  Chris 4  Chris
raja
Updated on 19-Oct-2021 07:40:30

Advertisements