👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.
In Python, how to sort a Pandas dataframe by column ?
In Python, you can sort a Pandas dataframe by a given column with the .sort_values()
method. Let's consider the following dataframe:
col1 col2 col3
0 Beta 1 4
1 Alpha 2 7
2 Charly 3 4
The following command sorts the dataframe by column col1
(ascending):
>>> df.sort_values(['col1'])
col1 col2 col3
1 Alpha 2 7
0 Beta 1 4
2 Charly 3 4
The following command sorts the dataframe by column col2
(descending):
>>> df.sort_values(['col2'], ascending = False)
col1 col2 col3
2 Charly 3 4
1 Alpha 2 7
0 Beta 1 4
The following command sorts the dataframe by column col3
, then col2
(ascending):
>>> df.sort_values(['col3', 'col2'])
col1 col2 col3
0 Beta 1 4
2 Charly 3 4
1 Alpha 2 7