Python Pandas | Swap levels of a MultiIndex

Learn, how to swap levels of a 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 Swap levels of a MultiIndex?

To swap levels of a MultiIndex in Python Pandas, we use pandas.MultiIndex.swaplevel() method is used. It accepts levels of the indices to be swapped, and returns a DataFrame with swapped levels in MultiIndex.

Syntax for Swapping levels of a MultiIndex

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 program to swap levels of a 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_ids', 'names', 'age'))

# display the Multiindex
print("The MultiIndex...\n",mi)
print()

# Get the levels in MultiIndex
print("The levels in MultiIndex...\n",mi.levels)
print()

# Swap levels 0 and 1 of a MultiIndex
print("Swap levels...\n",mi.swaplevel(0,1))
print()

# Swap levels 0 and 2 of a MultiIndex
print("Swap levels...\n",mi.swaplevel(0,2))
print()

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'])

Python Pandas Programs »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.