Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
s = pd.Series(['p', 'q', 'r', 's'], index=[3, 2, 4, 5])
s.sort_index()
Out[2]:
2    q
3    p
4    r
5    s
dtype: object

Sort Descending

In [3]:
s.sort_index(ascending=False)
Out[3]:
5    s
4    r
3    p
2    q
dtype: object

Sort Inplace

In [4]:
s.sort_index(inplace=True)
s
Out[4]:
2    q
3    p
4    r
5    s
dtype: object

By default NaNs are put at the end, but use na_position to place them at the beginning

In [5]:
s = pd.Series(['p', 'q', 'r', 's'], index=[3, 2, 4, np.nan])
s.sort_index(na_position='first')
Out[5]:
NaN    s
2.0    q
3.0    p
4.0    r
dtype: object

Specify index level to sort

In [6]:
arrays = [np.array(['xx', 'xx', 'ff', 'ff',
                    'bb', 'bb', 'br', 'br']),
          np.array(['two', 'one', 'two', 'one',
                    'two', 'one', 'two', 'one'])]
In [7]:
s = pd.Series([2, 3, 4, 5, 6, 7, 8, 9], index=arrays)
s.sort_index(level=1)
Out[7]:
bb  one    7
br  one    9
ff  one    5
xx  one    3
bb  two    6
br  two    8
ff  two    4
xx  two    2
dtype: int64

Does not sort by remaining levels when sorting by levels

In [8]:
s.sort_index(level=1, sort_remaining=False)
Out[8]:
xx  one    3
ff  one    5
bb  one    7
br  one    9
xx  two    2
ff  two    4
bb  two    6
br  two    8
dtype: int64