Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame({
     'c1': ['P', 'P', 'Q', np.nan, 'S', 'R'],
     'c2': [2, 4, 9, 8, 7, 5],
     'c3': [0, 4, 9, 5, 2, 3],
})
df
Out[2]:
c1 c2 c3
0 P 2 0
1 P 4 4
2 Q 9 9
3 NaN 8 5
4 S 7 2
5 R 5 3

Sort by c1:

In [3]:
df.sort_values(by=['c1'])
Out[3]:
c1 c2 c3
0 P 2 0
1 P 4 4
2 Q 9 9
5 R 5 3
4 S 7 2
3 NaN 8 5

Sort by multiple columns:

In [4]:
df.sort_values(by=['c1', 'c2'])
Out[4]:
c1 c2 c3
0 P 2 0
1 P 4 4
2 Q 9 9
5 R 5 3
4 S 7 2
3 NaN 8 5

Sort Descending:

In [5]:
df.sort_values(by='c1', ascending=False)
Out[5]:
c1 c2 c3
4 S 7 2
5 R 5 3
2 Q 9 9
0 P 2 0
1 P 4 4
3 NaN 8 5

Putting NAs first:

In [6]:
df.sort_values(by='c1', ascending=False, na_position='first')
Out[6]:
c1 c2 c3
3 NaN 8 5
4 S 7 2
5 R 5 3
2 Q 9 9
0 P 2 0
1 P 4 4