Python Pandas - Return MultiIndex with requested level removed


To return MultiIndex with requested level removed, use the MultiIndex.droplevel() method in Pandas. Set the level 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. The level is 1 i.e. level 1 gets dropped” −

print("\nMulti-index after dropping a level...\n",multiIndex.droplevel(1))

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
# The level is 1 i.e. level 1 gets dropped
print("\nMulti-index after dropping a level...\n",multiIndex.droplevel(1))

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

Updated on: 19-Oct-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements