Python Pandas - How to create a MultiIndex with names of each of the index levels

PythonServer Side ProgrammingProgramming

To create a MultiIndex, use the pandas.MultiIndex.from_arrays() method. To set names of each of the index levels, use the names 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, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

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, names=('ranks', 'student'))

Display the Multiindex −

print("The Multi-index...\n",multiIndex)

Get the names of levels in Multiindex −

print("\nThe names of levels in Multi-index...\n",multiIndex.names)

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, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

# 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, names=('ranks', 'student'))

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

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

Output

This will produce the following output −

The Multi-index...
MultiIndex([(1, 'John'),
   (2, 'Tim'),
   (3, 'Jacob'),
   (4, 'Chris'),
   (5, 'Keiron')],
   names=['ranks', 'student'])

The names of levels in Multi-index...
['ranks', 'student']
raja
Published on 19-Oct-2021 06:47:38
Advertisements