Ben Chuanlong Du's Blog

It is never too late to learn.

Sort a pandas DataFrame

In [4]:
import pandas as pd
In [5]:
df = pd.DataFrame({"x": [1, 2, 3, 4, 5], "a": [5, 4, 3, 2, 1]})

df.head()
Out[5]:
a x
0 5 1
1 4 2
2 3 3
3 2 4
4 1 5
In [8]:
df.sort_values("a")
Out[8]:
a x
4 1 5
3 2 4
2 3 3
1 4 2
0 5 1
In [24]:
a = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]})

a.head()
Out[24]:
x y
0 1 5
1 2 4
2 3 3
3 4 2
4 5 1
In [25]:
a.sort_values("y", inplace=True)
a
Out[25]:
x y
4 5 1
3 4 2
2 3 3
1 2 4
0 1 5
In [ ]:
 

Comments