Q:

Python Pandas | Swap levels of a MultiIndex

belongs to collection: Python Pandas Programs

0

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 (ij) that can be intstr 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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python Pandas | Rearrange levels using level name ... >>
<< Python Pandas | Set levels on a MultiIndex...