Python Pandas - Return MultiIndex with requested level removed using the level name

PythonServer Side ProgrammingProgramming

To return MultiIndex with requested level removed using the level name, use the MultiIndex.droplevel() method and set the level (level name) to be removed as an argument.

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 = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]

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'))

Drop a specific level from MultiIndex. The level to be dropped is set as the level name in parameter i.e.

# level name 'student' gets dropped −

print("\nMulti-index after dropping a level...\n",multiIndex.droplevel('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 = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]

# 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)

# Drop a specific level from MultiIndex
# The level to be dropped is set as the level name in parameter i.e.
# level name 'student' gets dropped
print("\nMulti-index after dropping a level...\n",multiIndex.droplevel('student'))

Output

This will produce the following output −

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

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

Multi-index after dropping a level...
   Int64Index([2, 4, 3, 1], dtype='int64', name='ranks')
raja
Published on 19-Oct-2021 07:57:35
Advertisements