Home > OS >  Sort grouped dataframe
Sort grouped dataframe

Time:09-30

Now I have a dataframe below.

 Type  Major   GPA   
  1      A     0   
  2      B     1   
  3      C     0   
  4      A     0   
  5      B     0   
  6      C     1

I would like to groupby('Major', sort=False), but sort the outer group by referencing col 'GPA' The desired dataframe would be like this:

  Type  Major   GPA   
  2      B     1   
  5      B     0   
  6      C     1   
  3      C     0   
  1      A     0   
  4      A     0

How this can be done? Thanks!!

CodePudding user response:

Let us use transform create the additional key

out = df.assign(key = df.groupby('Major')['GPA'].transform('sum')).sort_values(['key','Major','GPA'],ascending = [False,True,False]).drop('key',1)
Out[37]: 
   Type Major  GPA
1     2     B    1
4     5     B    0
5     6     C    1
2     3     C    0
0     1     A    0
3     4     A    0

CodePudding user response:

This might work:

def my_order(x):
    order = {'B': 0, 'C': 1, 'A': 2}
    return order[x]

df.sort_values(['Major', 'GPA'], ascending=[True, False], key=my_order)
  • Related