VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-sort-grouped-pandas-dataframe-by-group-size/

⇱ How to sort grouped Pandas dataframe by group size ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to sort grouped Pandas dataframe by group size ?

Last Updated : 23 Jul, 2025

In this article, we will discuss how to sort grouped data based on group size in Pandas.

Functions used

Here we will pass the inputs through the list as a dictionary data structure.

  • groupby(): groupby() is used to group the data based on the column values.
  • size(): This is used to get the size of the data frame.
  • sort_values(): This function sorts a data frame in Ascending or Descending order of passed Column.

The task is straightforward, for a given dataframe first we need to group by any column as per requirement and then arrange the grouped values of the column according to their size. By size here we mean how many times a value has appeared in a column or its frequency.

Example 1:

Output:

👁 Image
👁 Image

Example 2:

Output:

👁 Image
👁 Image

We can also group the multiple columns. The syntax remains the same, but we need to pass the multiple columns in a list and pass the list in groupby()

Syntax:

dataframe.groupby([column1,column2,.column n]).size().sort_values(ascending=True)

Example 3:

Comment