Home »
Python »
Python Programs
Return MultiIndex with multiple levels removed using the level names in Python Pandas
Learn, how to return MultiIndex with multiple levels removed using the level names in Python Pandas?
By IncludeHelp Last updated : April 10, 2023
MultiIndex Object
In Python Pandas, the MultiIndex object is the hierarchical analogue of the standard Index object which typically stores the axis labels in pandas objects. You can consider that MultiIndex is an array of unique tuples.
The pandas.MultiIndex.from_arrays() method is used to create a MultiIndex, and the names parameter is used to set names of each of the index levels.
Read: Create a MultiIndex with the names of each of the index levels
How to return MultiIndex with multiple levels removed using the level names?
To return MultiIndex with multiple levels removed using the level names, pandas.MultiIndex.droplevel() method is used. This method accepts int, str, or list-like parameters. If the parameter is a string then it must be the name of a level, if list-like, elements must be names or indexes of levels. And, the method returns either MultiIndex or Index. If the resulting index has only 1 level left, the result will be of Index type, not MultiIndex.
Syntax
MultiIndex.droplevel(level=0)
To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Python program to return MultiIndex with multiple levels removed using the level names
# Import the pandas package
import pandas as pd
# Create arrays
employees = [
['E101', 'E102', 'E102', 'E103'],
['Alex', 'Alvin', 'Deniel', 'Jenny'],
[21, 19, 15, 17]
]
# create a Multiindex using from_arrays()
mi = pd.MultiIndex.from_arrays(employees, names=('emp_id', 'name', 'age'))
# display the Multiindex
print("The MultiIndex...\n",mi)
print()
# Get the levels in MultiIndex
print("The levels in MultiIndex...\n",mi.levels)
print()
# Dropping one level
print("Dropping one level (age)...")
print(mi.droplevel(['age']))
print()
# Dropping two levels
print("Dropping two levels (emp_id, age)...")
print(mi.droplevel(['emp_id', 'age']))
print()
Output
The MultiIndex...
MultiIndex([('E101', 'Alex', 21),
('E102', 'Alvin', 19),
('E102', 'Deniel', 15),
('E103', 'Jenny', 17)],
names=['emp_id', 'name', 'age'])
The levels in MultiIndex...
[['E101', 'E102', 'E103'], ['Alex', 'Alvin', 'Deniel', 'Jenny'], [15, 17, 19, 21]]
Dropping one level (age)...
MultiIndex([('E101', 'Alex'),
('E102', 'Alvin'),
('E102', 'Deniel'),
('E103', 'Jenny')],
names=['emp_id', 'name'])
Dropping two levels (emp_id, age)...
Index(['Alex', 'Alvin', 'Deniel', 'Jenny'], dtype='object', name='name')
Python Pandas Programs »