pandas.MultiIndex.sortlevel#

MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True, na_position='first')[source]#

Sort MultiIndex at the requested level.

This method is useful when dealing with MultiIndex objects, allowing for sorting at a specific level of the index. The function preserves the relative ordering of data within the same level while sorting the overall MultiIndex. The method provides flexibility with the ascending parameter to define the sort order and with the sort_remaining parameter to control whether the remaining levels should also be sorted. Sorting a MultiIndex can be crucial when performing operations that require ordered indices, such as grouping or merging datasets. The na_position argument is important in handling missing values consistently across different levels.

Parameters:
levellist-like, int or str, default 0

If a string is given, must be a name of the level. If list-like must be names or ints of levels.

ascendingbool, default True

False to sort in descending order. Can also be a list to specify a directed ordering.

sort_remainingbool, default True

If True, sorts by the remaining levels after sorting by the specified level.

na_position{‘first’ or ‘last’}, default ‘first’

Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.

Added in version 2.1.0.

Returns:
sorted_indexpd.MultiIndex

Resulting index.

indexernp.ndarray[np.intp]

Indices of output values in original index.

See also

MultiIndex

A multi-level, or hierarchical, index object for pandas objects.

Index.sort_values

Sort Index values.

DataFrame.sort_index

Sort DataFrame by the index.

Series.sort_index

Sort Series by the index.

Examples

>>> mi = pd.MultiIndex.from_arrays([[0, 0], [2, 1]])
>>> mi
MultiIndex([(0, 2),
            (0, 1)],
           )
>>> mi.sortlevel()
(MultiIndex([(0, 1),
            (0, 2)],
           ), array([1, 0]))
>>> mi.sortlevel(sort_remaining=False)
(MultiIndex([(0, 2),
            (0, 1)],
           ), array([0, 1]))
>>> mi.sortlevel(1)
(MultiIndex([(0, 1),
            (0, 2)],
           ), array([1, 0]))
>>> mi.sortlevel(1, ascending=False)
(MultiIndex([(0, 2),
            (0, 1)],
           ), array([0, 1]))