首页 > 解决方案 > 过滤一列并在另一列上排名,而不在数据框中分组

问题描述

我有一个数据框有 4 列 student_name、total_marks、is_shortlisted、rank

我想根据 is_shortlisted = "Y" 的 total_marks 列对行进行排名。

样本输入数据:

name     total_marks   is_shortlisted
Aman       67              Y
Nitin      89              Y
Ankur      76              Y
Mohit      56              N
Ashish     64              Y

样本输出数据:

name     total_marks   is_shortlisted  rank 
Aman       67              Y            3
Nitin      89              Y            1
Ankur      76              Y            2
Mohit      56              N            nan
Ashish     64              Y            4

标签: pythonpython-3.xpandasdataframe

解决方案


loc与 一起使用rank

df.assign(rank=df.loc[df.is_shortlisted.eq('Y')].total_marks.rank(ascending=False))

     name  total_marks is_shortlisted  rank
0    Aman           67              Y   3.0
1   Nitin           89              Y   1.0
2   Ankur           76              Y   2.0
3   Mohit           56              N   NaN
4  Ashish           64              Y   4.0

推荐阅读