簡體   English   中英

分組並根據 Pandas 中的另一列對一列進行降序排名

[英]Groupby and descendingly rank one column based on another one in Pandas

對於下面的示例數據幀,我在grouby工作class和遞減排名score

    stu_id class    name  score
0        1     A    Jack     45
1        2     A   Oscar     75
2        3     B   Emile     60
3        4     B  Sophie     64
4        5     B     Jim     85
5        6     A  Thomas     55
6        7     A   David     60
7        8     B     Lee     60
8        9     B   Elvis     70
9       10     A   Frank     75
10      11     A   James     90

我試過了:

df['rank'] = df.groupby(['class'])['score'].rank(ascending=True)
df

結果:

    stu_id class    name  score  rank
0        1     A    Jack     45   1.0
1        2     A   Oscar     75   4.5
2        3     B   Emile     60   1.5
3        4     B  Sophie     64   3.0
4        5     B     Jim     85   5.0
5        6     A  Thomas     55   2.0
6        7     A   David     60   3.0
7        8     B     Lee     60   1.5
8        9     B   Elvis     70   4.0
9       10     A   Frank     75   4.5
10      11     A   James     90   6.0

但是我的預期輸出應該是這樣的,為什么我的代碼不起作用? 謝謝。

    stu_id class    name  score  rank
0        1     A    Jack     45     1
1        2     A   Oscar     75     4
2        3     B   Emile     60     1
3        4     B  Sophie     64     2
4        5     B     Jim     85     4
5        6     A  Thomas     55     2
6        7     A   David     60     3
7        8     B     Lee     60     1
8        9     B   Elvis     70     3
9       10     A   Frank     75     4
10      11     A   James     90     5

method='dense'

默認排名使用average來解決平局。 在A組中,奧斯卡和弗蘭克的得分相同,這與排名4和5有關。在'average'邏輯下,兩者都設置為4.5:(4+5)/2,那么下一個值排在第6位因為與它沒有聯系,詹姆斯就是這種情況。 使用'dense' ,關系被賦予較低的等級(在這種情況下為4 ),然后下一個不同的值在 5 處繼續排名。

df['rank'] = df.groupby(['class'])['score'].rank(method='dense').astype(int)

    stu_id class    name  score  rank
0        1     A    Jack     45     1
1        2     A   Oscar     75     4
2        3     B   Emile     60     1
3        4     B  Sophie     64     2
4        5     B     Jim     85     4
5        6     A  Thomas     55     2
6        7     A   David     60     3
7        8     B     Lee     60     1
8        9     B   Elvis     70     3
9       10     A   Frank     75     4
10      11     A   James     90     5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM