Python Pandas - Set only a single new specific level using the level name in a MultiIndex

PythonServer Side ProgrammingProgramming

To set only a single new specific level using the level name in a MultiIndex, use the MultiIndex.set_levels() method. The parameter level is used to set the level name.

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

Set the level in MultiIndex. We have set a new single specific level using the level name in the "level" parameter −

print("\nSet a new level in Multi-index...\n",multiIndex.set_levels(['Emma', 'Angelina', 'Scarlett', 'Jeni'], level = 'student'))

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

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

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

# set the level in MultiIndex
# We have set a new single specific level using the level name in the "level" parameter
print("\nSet a new level in Multi-index...\n",multiIndex.set_levels(['Emma', 'Angelina', 'Scarlett', 'Jeni'], level = 'student'))

Output

This will produce the following output −

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

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

Set a new level in Multi-index...
MultiIndex([(1, 'Scarlett'),
            (2,     'Jeni'),
            (3, 'Angelina'),
            (4,     'Emma')],
            names=['ranks', 'student'])
raja
Published on 19-Oct-2021 07:16:51
Advertisements