python - 过滤一列并在另一列上排名,而不在数据框中分组
问题描述
我有一个数据框有 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
解决方案
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
推荐阅读
- xcode - SwiftUI:无法使用 UIActivityViewController 共享图像
- vue.js - CopyWebpackPlugin 没有将静态文件复制到输出目录
- c++ - 从文本文件中逐字读取每一行并转换为int(无限循环或崩溃?)
- json - 使用 jq 将 JSON 的一个属性从多个连接到一个文件中
- ruby-on-rails - 我可以在交换机内部使用路由吗?
- karate - 空手道框架基本访问认证
- flutter - 颤振列未消耗并导致溢出
- r - R:用于 xml 的 httr SOAP POST 请求返回错误 - “不支持媒体类型”
- javascript - 如何将带有嵌套表格的 HTML 表格正确导出到 Excel?
- java - 如何在改造中拆分数据以在android中添加水平progressBar?