Swap levels of a MultiIndex
The pandas.MultiIndex.swaplevel() method is used to swap levels of a MultiIndex.
Syntax:
MultiIndex.swaplevel(i=- 2, j=- 1)
The method accepts two values (i, j) that can be int, str and their default values are -2 and -1. The method returns a new MultiIndex.
To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Python code to swap levels of a MultiIndex
Output:
The MultiIndex... MultiIndex([('E101', 'Alex', 21), ('E102', 'Alvin', 19), ('E102', 'Deniel', 15), ('E103', 'Jenny', 17)], names=['emp_ids', 'names', 'age']) The levels in MultiIndex... [['E101', 'E102', 'E103'], ['Alex', 'Alvin', 'Deniel', 'Jenny'], [15, 17, 19, 21]] Swap levels... MultiIndex([( 'Alex', 'E101', 21), ( 'Alvin', 'E102', 19), ('Deniel', 'E102', 15), ( 'Jenny', 'E103', 17)], names=['names', 'emp_ids', 'age']) Swap levels... MultiIndex([(21, 'Alex', 'E101'), (19, 'Alvin', 'E102'), (15, 'Deniel', 'E102'), (17, 'Jenny', 'E103')], names=['age', 'names', 'emp_ids'])need an explanation for this answer? contact us directly to get an explanation for this answer