Python Pandas - Return MultiIndex with multiple levels removed using the level names


To return MultiIndex with multiple levels removed using the level names, use the MultiIndex.droplevel() method and set the multiple levels (level name) to be removed as arguments.

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'], [50, 30, 40, 70]]

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=('rank', 'student', 'points'))

Drop a specific level from MultiIndex. The levels to be dropped is set as the level names in parameter i.e. level name 'student' and 'rank' gets dropped −

print("\nMulti-index after dropping two levels...\n",multiIndex.droplevel(['rank', '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'], [50, 30, 40, 70]]

# 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=('rank', 'student', 'points'))

# 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 levels to be dropped is set as the level names in parameter i.e.
# level name 'student' and 'rank' gets dropped
print("\nMulti-index after dropping two levels...\n",multiIndex.droplevel(['rank', 'student']))

Output

This will produce the following output −

The Multi-index...
MultiIndex([(2, 'Peter', 50),
            (4, 'Chris', 30),
            (3,  'Andy', 40),
            (1, 'Jacob', 70)],
            names=['rank', 'student', 'points'])

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

Multi-index after dropping two levels...
   Int64Index([50, 30, 40, 70], dtype='int64', name='points')

Updated on: 19-Oct-2021

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements