Home > Software design >  Groupby and sort Pandas
Groupby and sort Pandas

Time:10-21

I have a dataframe:

df = pd.DataFrame({ 
    'Metric': ['Total Assets', 'Total Promo', 'Total Assets', 'Total Promo'],
    'Risk': ['High', 'High','Low', 'Low'],
    '2021': [ 200, 100, 400, 50]})

I want to groupby the Metric column and sort by '2021' column.

I tried:

df = df.sort_values(['2021'],ascending=False).groupby(['Metric', 'Risk'])

But I get the following output:

<pandas.core.groupby.generic.DataFrameGroupBy object at 0x00000213CA672B48>

The output should look like:

df = pd.DataFrame({ 
    'Metric': ['Total Assets', 'Total Assets', 'Total Promo', 'Total Promo'],
    'Risk': ['Low', 'High', 'High', 'Low'],
    '2021': [ 400, 200, 100,  50]})

CodePudding user response:

If I understand you right, you want to sort by column "Metric" (ascending) and then "2021" (descending):

df = df.sort_values(["Metric", "2021"], ascending=[True, False])
print(df)

Prints:

         Metric  Risk  2021
0  Total Assets   Low   400
1  Total Assets  High   200
2   Total Promo  High   100
3   Total Promo   Low    50
  • Related