Home »
Python »
Python Programs
Rearrange levels using level name in MultiIndex in Python Pandas
Learn, how to rearrange levels using level name in MultiIndex 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 rearrange levels using level name in MultiIndex?
To rearrange levels using level name in MultiIndex, we use pandas.MultiIndex.reorder_levels() method. The method accepts list representing a new level order that can be either list of int or list of str and return the MultiIndex.
Syntax to rearrange levels using level name
MultiIndex.reorder_levels(order)
Python program to rearrange levels using level name in MultiIndex
# 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()
# Reorder levels
print("Reorder levels (name, age, emp_id)...")
print(mi.reorder_levels(order=['name','age','emp_id']))
print()
# Reorder levels
print("Reorder levels (emp_id, age, name)...")
print(mi.reorder_levels(order=['emp_id','age','name']))
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]]
Reorder levels (name, age, emp_id)...
MultiIndex([( 'Alex', 21, 'E101'),
( 'Alvin', 19, 'E102'),
('Deniel', 15, 'E102'),
( 'Jenny', 17, 'E103')],
names=['name', 'age', 'emp_id'])
Reorder levels (emp_id, age, name)...
MultiIndex([('E101', 21, 'Alex'),
('E102', 19, 'Alvin'),
('E102', 15, 'Deniel'),
('E103', 17, 'Jenny')],
names=['emp_id', 'age', 'name'])
Python Pandas Programs »