Thursday, November 20, 2025
HomeLanguagesSort Dataframe according to row frequency in Pandas

Sort Dataframe according to row frequency in Pandas

In this article, we will discuss how to use count() and sort_values() in pandas. So the count in pandas counts the frequency of elements in the dataframe column and then sort sorts the dataframe according to element frequency.

  • count(): This method will show you the number of values for each column in your DataFrame.
  • sort_values(): This method helps us to sort our dataframe. In this method, we pass the column and our data frame is sorted according to this column.

Example 1: Program to sort data frame in descending order according to the element frequency.

Python




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj',
                            'Kamal', 'Rohan', 'Robin'],
                     
                   'age': [22, 22, 21, 20, 21, 24, 20]})
  
# print dataframe
print(df)
  
# use count() and sort()
df = df.groupby(['Name'])['age'].count().reset_index(
  name='Count').sort_values(['Count'], ascending=False)
  
# print dataframe
print(df)


Output:

Example 2: Program to sort data frame in ascending order according to the element frequency.

Python




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj',
                            'Kamal', 'Rohan', 'Robin'],
                     
                   'age': [22, 22, 21, 20, 21, 24, 20]})
  
# print dataframe
print(df)
  
# use count() and sort()
df = df.groupby(['Name'])['age'].count().reset_index(
  name='Count').sort_values(['Count'], ascending=True)
  
# print dataframe
print(df)


Output:

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6775 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6903 POSTS0 COMMENTS
Ted Musemwa
7159 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS