Instagram
youtube
Facebook
Twitter

Orderby

Sorting in Pandas

  • Pandas comes with a function sort_values() which sorts the data.
  • sort_values() can sort the data frame in both ascending and descending order. 

Syntax of sort_values():

​DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)

Parameters:

  • by: str or list of str

  • axis : {0 or ‘index’, 1 or ‘columns’}, default 0

  • ascending: bool or list of bool, default True

  • in_place: bool, default False

  • kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’
    Choice of sorting algorithm. See also NumPy.sort() for more information. mergesort and stable are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.

  • na_position : {‘first’, ‘last’}, default ‘last’
    Puts NaNs at the beginning if first; last puts NaNs at the end.

  • ignore_index: bool, default False


Examples:

Sorting the given dataframe in Ascending Order:

import pandas as pd 
  
# creating and initializing a nested list  
data = [['The Matrix', 1999], ['Monster''s Inc', 2001], ['Call me by your name', 2017], ['Star Wars Episode-1', 1999], ['Star Wars Episode-2', 2003], ['Star Wars Episode-3', 2005], ['Love Rosie', 2014], ['Perfect Sence', 2011]]
  
# creating a pandas dataframe 
df = pd.DataFrame(data,columns=['Movies','Year']) 
print(df)
print('------------------------------------------')
# Sorting by column 'Movies' 
sf = df.sort_values('Movies') 
print(sf)
print('------------------------------------------')
# Sorting by year
sf1 = df.sort_values('Year')
print(sf1)

Output:

                 Movies  Year
0            The Matrix  1999
1          Monsters Inc  2001
2  Call me by your name  2017
3   Star Wars Episode-1  1999
4   Star Wars Episode-2  2003
5   Star Wars Episode-3  2005
6            Love Rosie  2014
7         Perfect Sence  2011
------------------------------------------
                 Movies  Year
2  Call me by your name  2017
6            Love Rosie  2014
1          Monsters Inc  2001
7         Perfect Sence  2011
3   Star Wars Episode-1  1999
4   Star Wars Episode-2  2003
5   Star Wars Episode-3  2005
0            The Matrix  1999
------------------------------------------
                 Movies  Year
0            The Matrix  1999
3   Star Wars Episode-1  1999
1          Monsters Inc  2001
4   Star Wars Episode-2  2003
5   Star Wars Episode-3  2005
7         Perfect Sence  2011
6            Love Rosie  2014
2  Call me by your name  2017

Sorting in descending order:

sf1 = df.sort_values('Year',ascending=False)
print(sf1)

 Output:

                 Movies  Year
2  Call me by your name  2017
6            Love Rosie  2014
7         Perfect Sence  2011
5   Star Wars Episode-3  2005
4   Star Wars Episode-2  2003
1          Monsters Inc  2001
0            The Matrix  1999
3   Star Wars Episode-1  1999