簡體   English   中英

按列分組,對另一列進行排序並為python中的行分配排名

[英]Groupby a column, sort another column and assign rank to the rows in python

我在熊貓中有以下數據框“分數”。

identifier  name             score
D29650  abc10   115369-52-3  0.75
D29650  abc10   115369-52-4  0.34
D29651  abc11   115369-52-5  0.25
D29651  abc11   ls-132190    0.67
D29652  abc12   me1228           1.0
D29652  abc12   me 1228          0.875

我想對每個標識符中的分數列進行排序,並為每個條目分配一個排名。 我正在使用以下命令來做到這一點,但不確定如何給出排名。

score_new=scores.groupby(['identifier'],as_index=False).apply(lambda x:x.sort_values(by='score',ascending=False)).reset_index(drop=True)

所需的輸出是:

identifier  name             score  rank
D29650  abc10   115369-52-3  0.75   1
D29650  abc10   115369-52-4  0.34   2
D29651  abc11   ls-132190    0.67   1
D29651  abc11   115369-52-5  0.25   2 
D29652  abc12   me1228           1.0    1
D29652  abc12   me 1228          0.875  2

非常感謝這里的 Anh 幫助

用:

df['rank']=df.groupby('identifier')['score'].rank(ascending=False).astype('int32')

嘗試這個?

df1=df1.sort_values(['Identifier'],ascending=[True,True])
df1['Score']=df1.Name!=df1.Name.shift().fillna('edit')
df1.Score=df1.groupby('ID').Score.cumsum()+1

暫無
暫無

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

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