Python Pandas - Rearrange levels using level name in MultiIndex

PythonServer Side ProgrammingProgramming

To rearrange levels using level name in MultiIndex, use the MultiIndex.reorder_levels() method in Pandas. Pass the levels (level names) to be rearranged as arguments.

At first, import the required libraries −

import pandas as pd

MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −

arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −

multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))

Reorder levels of MultiIndex. The "order" parameter is used to set the level name in a form to reorder levels −

print("\nReorder levels in MultiIndex using level name...\n",multiIndex.reorder_levels(order=['student','rank','points']))

Example

Following is the code −

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))

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

# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# swap levels of MultiIndex using swaplevel()
# The 1st parameter is the first level of index to be swapped
# The 2nd parameter is the second level of index to be swapped
print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2))

# Reorder levels of MultiIndex
# The "order" parameter is used to set the level name in a form to reorder levels
print("\nReorder levels in MultiIndex using level name...\n",multiIndex.reorder_levels(order=['student','rank','points']))

Output

This will produce the following output −

The MultiIndex...
MultiIndex([(2, 'Peter', 50),
            (4, 'Chris', 30),
            (3,  'Andy', 40),
            (1, 'Jacob', 70)],
            names=['rank', 'student', 'points'])

The levels in MultiIndex...
   [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]]

Swap levels in MultiIndex...
MultiIndex([('Peter', 2, 50),
            ('Chris', 4, 30),
            ( 'Andy', 3, 40),
            ('Jacob', 1, 70)],
            names=['student', 'rank', 'points'])

Reorder levels in MultiIndex using level name...
MultiIndex([('Peter', 2, 50),
            ('Chris', 4, 30),
            ( 'Andy', 3, 40),
            ('Jacob', 1, 70)],
            names=['student', 'rank', 'points'])
raja
Published on 19-Oct-2021 08:05:45
Advertisements