2

I have a DF that looks like this;

   Group     Name     Rank     Group_Sales_Total
0  A         Dave     4        10
1  A         Tom      2        10
2  A         Sara     1        10
3  A         Raul     3        10
4  B         Chris    3        20
5  B         John     4        20
6  B         Aarti    1        20
7  B         Amen     2        20

What I would like to do is, sort each member of each group by their respective rank and then sort the groups by their respective sales total. The result i'm aiming for should look like this.

   Group     Name     Rank     Group_Sales_Total
0  B         Aarti    1        20
1  B         Amen     2        20
2  B         Chris    3        20
3  B         John     4        20
4  A         Sara     1        10
5  A         Tom      2        10
6  A         Raul     3        10
7  A         Dave     4        10

I am able to sort the ranking out correctly for each group using;

DF.groupby('Group').apply(pd.DataFrame.sort_values, 'Rank', ascending=True).reset_index(drop=True)

However, when I also try to sort it by the group sales total, the sort either doesn't occur or messes up the order of the ranking. I've tried the following;

DF.groupby('Group').apply(pd.DataFrame.sort_values, ['Rank','Group_Sales_Total'], ascending=[True, False]).reset_index(drop=True)

Any help/insight on getting to the output would be greatly appreciated.

Kind regards

Amen_90
  • 310
  • 2
  • 9
  • Does this answer your question? [Sort pandas DataFrame by multiple columns and duplicated index](https://stackoverflow.com/questions/58689919/pandas-sort-a-dataframe-based-on-multiple-columns) – David Erickson Sep 14 '20 at 09:32
  • @wwnde no... I did not take your answer and post in the comments (per the comment you deleted). I typed it at same time or just before you did – David Erickson Sep 14 '20 at 09:32
  • No problem @wwnde , I have deleted that comment since it appears to be 1 minute after your answer :) – David Erickson Sep 14 '20 at 09:50

1 Answers1

2
 df.sort_values(['Group','Rank','Group_Sales_Total'], ascending=[False, True, False])



 Group   Name  Rank  Group_Sales_Total
6     B  Aarti     1                 20
7     B   Amen     2                 20
4     B  Chris     3                 20
5     B   John     4                 20
2     A   Sara     1                 10
1     A    Tom     2                 10
3     A   Raul     3                 10
0     A   Dave     4                 10
wwnde
  • 26,119
  • 6
  • 18
  • 32