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

PythonServer Side ProgrammingProgramming

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in descending order, use sort_values(). The size() method is used to get the dataframe size.

For descending order sort, use the following in sort_values() −

ascending=False

At first, create a pandas dataframe −

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

Next, group according to Reg_Price column and sort in descending order −

dataFrame.groupby('Reg_Price').size().sort_values(ascending=False)

Example

Following is the code

import pandas as pd

# dataframe with one of the columns as Reg_Price
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)

print"DataFrame...\n",dataFrame

# group according to Reg_Price column and sort in descending order
print"\nSorted in Descending order...";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=False))

Output

This will produce the following output −

DataFrame...
        Car Reg_Price
0       BMW      1000
1     Lexus      1400
2      Audi      1000
3  Mercedes       900
4    Jaguar      1700
5   Bentley       900

Sorted in Descending order...
Reg_Price
1000    2
900     2
1700    1
1400    1
dtype: int64
raja
Published on 13-Sep-2021 08:03:05
Advertisements