Double rating in python after group

I made a group that made the data frame look like the example below.

df = pd.DataFrame({'a': ['A', 'A','A', 'B', 'B','B'], 'b': ['A1', 'A2','A3' ,'B1', 'B2','B3'], 'c': ['2','3','4','5','6','1'] })

>>> df
   a   b  c
0  A  A1  2
1  A  A2  3
2  A  A3  4
3  B  B1  5
4  B  B2  6
5  B  B3  1

desired output

>>> df
       a   b  c
    4  B  B2  6
    3  B  B1  5
    5  B  B3  1       
    2  A  A3  4
    1  A  A2  3
    0  A  A1  2 

As you can see, this is a double ranking based on column a, then column b. First, we start with the highest value, which is B, and inside B we also start with the highest value B2.

how can i do this in python please

+4
source share
3 answers

you can first find the maxima in each group and sort your DF descending along these local maxima and columns c:

In [49]: (df.assign(x=df.groupby('a')['c'].transform('max'))
            .sort_values(['x','c'], ascending=[0,0])
            .drop('x',1))
Out[49]:
   a   b  c
4  B  B2  6
3  B  B1  5
5  B  B3  1
2  A  A3  4
1  A  A2  3
0  A  A1  2
+2
source

Using

In [1072]: df.sort_values(by=['a', 'c'], ascending=[False, False])
Out[1072]:
   a   b  c
4  B  B2  6
3  B  B1  5
5  B  B3  1
2  A  A3  4
1  A  A2  3
0  A  A1  2
+2
source

, max , Categorical max sort_values :

c = df.groupby('a')['c'].max().sort_values(ascending=False)
print (c)
a
B    6
A    4
Name: c, dtype: object

df['a'] = pd.Categorical(df['a'], categories=c.index, ordered=True)
df = df.sort_values(by=['a', 'c'], ascending=[True, False])
print (df)
   a   b  c
4  B  B2  6
3  B  B1  5
5  B  B3  1
2  A  A3  4
1  A  A2  3
0  A  A1  2
+2

Source: https://habr.com/ru/post/1695523/


All Articles