+1 vote
in Programming Languages by (8.7k points)
How can I sort the Pandas DataFrame by the values of column(s)?

I am looking for something similar to "ORDER BY" of SQL.

1 Answer

0 votes
by (17k points)

There is a function called sort_values() which is very similar to "ORDER BY" of SQL. You can use it to sort the DataFrame by one column or multiple columns, in ascending or in descending order. By default, it sorts in ascending order. Check the following examples.

>>> import pandas as pd
>>> df=pd.DataFrame({'Fruit':['banana','apple','orange','mango'], 'Price':[23,12,45,9], 'Stock':[3500,2300,4500,4200]})
>>> df
    Fruit  Price  Stock
0  banana     23   3500
1   apple     12   2300
2  orange     45   4500
3   mango      9   4200

Sort by one column
>>> df.sort_values(by=['Fruit'])
    Fruit  Price  Stock
1   apple     12   2300
0  banana     23   3500
3   mango      9   4200
2  orange     45   4500

Sort by mlutiple columns
>>> df.sort_values(by=['Fruit','Price'])
    Fruit  Price  Stock
1   apple     12   2300
0  banana     23   3500
3   mango      9   4200
2  orange     45   4500

Sort in descending order
>>> df.sort_values(by=['Fruit','Price'], ascending=False)
    Fruit  Price  Stock
2  orange     45   4500
3   mango      9   4200
0  banana     23   3500
1   apple     12   2300

...