Python Pandas - How to Sort MultiIndex at a specific level

PythonServer Side ProgrammingProgramming

To create a MultiIndex, use the from_arrays() method. However, to sort MultiIndex at a specific level, use the multiIndex.sortlevel() method in Pandas. Set the level as an argument.

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

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

Sort MultiIndex. The specific level to sort is set as a parameter i.e. level 1 here −

print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))

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

# 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 specific level to sort is set as a parameter i.e. level 1 here
print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))

Output

This will produce the following output −

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

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

Sort MultiIndex at the requested level...
(MultiIndex([(3, 'Andy'),
             (4, 'Chris'),
             (1, 'Jacob'),
             (2, 'Peter')],
             names=['ranks', 'student']), array([2, 1, 3, 0], dtype=int64))
raja
Updated on 19-Oct-2021 07:47:58

Advertisements