Python Pandas - How to Sort MultiIndex


To create a MultiIndex, use the from_arrays() method. However, to sort MultiIndex, use the multiIndex.sortlevel(). method in Pandas.

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], ['John', 'Tim', 'Jacob', 'Chris']]

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

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

Sort MultiIndex. The default sorts at level 0 −

print("\nSort MultiIndex...\n",multiIndex.sortlevel())

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], ['John', 'Tim', 'Jacob', 'Chris']]

# 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=('ranks', 'student'))

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

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

# Sort MultiIndex
# The default sorts at level 0
print("\nSort MultiIndex...\n",multiIndex.sortlevel())

Output

This will produce the following output −

The Multi-index...
MultiIndex([(2,  'John'),
            (4,   'Tim'),
            (3, 'Jacob'),
            (1, 'Chris')],
            names=['ranks', 'student'])

The levels in Multi-index...
   [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]

Sort MultiIndex...
(MultiIndex([(1, 'Chris'),
             (2,  'John'),
             (3, 'Jacob'),
             (4,   'Tim')],
names=['ranks', 'student']), array([3, 0, 2, 1], dtype=int64))

Updated on: 19-Oct-2021

769 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements