Python - Return index with a specific level removed

PythonServer Side ProgrammingProgramming

To return index with a specific level removed, use the multiIndex.droplevel() method in Pandas. At first, import the required libraries -

import pandas as pd

Create a multi-index. The names parameter sets the names for the levels in the index

multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]],
names=['a', 'b', 'c', 'd'])

Dropping a level. We have passed the position of the level to be removed as a parameter −

print("\nDropping a level...\n",multiIndex.droplevel(3))

Example

Following is the code −

import pandas as pd

# Create a multi-index
# The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]],
names=['a', 'b', 'c', 'd'])

# display the multi-index
print("Multindex...\n",multiIndex)

# Dropping a level
# We have passed the position of the level to be removed as a parameter
print("\nDropping a level...\n",multiIndex.droplevel(3))

Output

This will produce the following output −

Multindex...
MultiIndex([( 5, 15, 25, 35),(10, 20, 30, 40)],names=['a', 'b', 'c', 'd'])

Dropping a level...
MultiIndex([( 5, 15, 25),(10, 20, 30)],names=['a', 'b', 'c'])
raja
Published on 13-Oct-2021 09:08:59
Advertisements