Python Pandas - How to Sort MultiIndex at a specific level in descending order

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. To sort in descending order, use the ascending parameter and set to False.

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. We have sort in descending order using the "ascending" order with value "False" −

print("
Sort MultiIndex at the requested level in descending order...
",multiIndex.sortlevel(1, ascending=False))

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...
",multiIndex) # get the levels in MultiIndex print("
The levels in Multi-index...
",multiIndex.levels) # Sort MultiIndex # The specific level to sort is set as a parameter i.e. level 1 here # We have sort in descending order using the "ascending" order with value "False" print("
Sort MultiIndex at the requested level in descending order...
",multiIndex.sortlevel(1, ascending=False))

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 in descending order...
(MultiIndex([(2, 'Peter'),
             (1, 'Jacob'),
             (4, 'Chris'),
             (3,  'Andy')],
             names=['ranks', 'student']), array([0, 3, 1, 2], dtype=int64))
raja
Updated on 19-Oct-2021 07:50:58

Advertisements