Python – Sort grouped Pandas dataframe by group size?

PythonServer Side ProgrammingProgramming

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

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

ascending=True

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)

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

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

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"Sorted in Descending order...\n";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=False))

# group according to Reg_Price column and sort in ascending order
print"Sorted in Ascending order...\n";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))

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
Sorted in Ascending order...

Reg_Price
1400    1
1700    1
900     2
1000    2
dtype: int64
raja
Published on 13-Sep-2021 07:25:48
Advertisements