Python – Ascending Order Sort grouped Pandas dataframe by group size?

In Pandas, you can group a DataFrame and sort the groups by their size in ascending order. This is useful for understanding the distribution of data across different categories.

Understanding Group Size Sorting

To sort grouped DataFrames by group size in ascending order, we combine three methods:

  • groupby() ? Groups DataFrame by specified column
  • size() ? Returns the count of rows in each group
  • sort_values(ascending=True) ? Sorts groups by size in ascending order

Basic Example

Let's create a DataFrame and sort groups by size in ascending order ?

import pandas as pd

# Create a DataFrame with car data
dataFrame = pd.DataFrame({
    "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
    "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
})

print("Original DataFrame:")
print(dataFrame)
Original DataFrame:
        Car  Reg_Price
0       BMW       1000
1     Lexus       1400
2      Audi       1000
3  Mercedes        900
4    Jaguar       1700
5   Bentley        900

Sorting Groups by Size

Now group by the 'Reg_Price' column and sort by group size in ascending order ?

import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
    "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
})

# Group by Reg_Price and sort by group size (ascending)
result = dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)

print("Groups sorted by size (ascending):")
print(result)
Groups sorted by size (ascending):
Reg_Price
1400    1
1700    1
900     2
1000    2
dtype: int64

Understanding the Output

The output shows each unique value from the 'Reg_Price' column and how many rows belong to each group:

  • Price groups 1400 and 1700 have 1 car each (smallest groups)
  • Price groups 900 and 1000 have 2 cars each (larger groups)

Descending Order Sort

To sort groups by size in descending order, set ascending=False ?

import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
    "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
})

# Sort by group size in descending order
result = dataFrame.groupby('Reg_Price').size().sort_values(ascending=False)

print("Groups sorted by size (descending):")
print(result)
Groups sorted by size (descending):
Reg_Price
900     2
1000    2
1400    1
1700    1
dtype: int64

Conclusion

Use groupby().size().sort_values(ascending=True) to sort DataFrame groups by their size in ascending order. This helps identify which categories have the fewest or most occurrences in your data.

Updated on: 2026-03-26T01:37:04+05:30

574 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements