如何在Python中的不同列表中对同一位置的每个项目进行排名?
我是 R 程序员,但需要使用 python 实现表格中的排名。假设我有一列“测试”,其中包含数字列表:
df = pd.DataFrame({"test":[[1,4,7], [4,2,6], [3,8,1]]})
我希望对行(列表)中同一位置的每个项目进行排名,并对所有排名进行平均以获得最终分数:
预期:
test rank_list final_score
0 [1, 4, 7] [1, 2, 3] 2
1 [4, 2, 6] [3, 1, 2] 2
2 [3, 8, 1] [2, 3, 1] 2
我知道这不是一个一个很好的例子,所有最终分数都是相同的,但如果有数百行,结果会有所不同。我希望我能清楚地描述问题,如果没有,请随时提问。
我不知道我是否可以在 pandas 中做到这一点,但我尝试了 zip + scipy,但是 scipy.stats.rankdata 没有给出同一索引处项目的排名:
l = list(dff["test"])
ranks_list = [scipy.stats.rankdata(x) for x in zip(*l)] # not right
estimated_rank = [sum(x) / len(x) for x in ranks_list]
我对任何各种套餐,以方便为准。谢谢你!
I am R programmer, but need to achieve rankings in a table using python. Let's say I have a column "test" with a list of number lists:
df = pd.DataFrame({"test":[[1,4,7], [4,2,6], [3,8,1]]})
I expected to rank each item at the same location across rows (lists), and average all ranks to get a final score:
expected:
test rank_list final_score
0 [1, 4, 7] [1, 2, 3] 2
1 [4, 2, 6] [3, 1, 2] 2
2 [3, 8, 1] [2, 3, 1] 2
I know it is not a good example that all final scores are the same, but with hundreds of rows, the results will be various. I hope I describe the questions clearly, but if not, please feel free to ask.
I don't know if I can do it in pandas, but I tried zip + scipy, but scipy.stats.rankdata
did not give the rank on item at the same index:
l = list(dff["test"])
ranks_list = [scipy.stats.rankdata(x) for x in zip(*l)] # not right
estimated_rank = [sum(x) / len(x) for x in ranks_list]
I am open to any kinds of packages, whichever is convenient. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
rank
方法来获取排名。然后使用agg
获取列rank_list
列表的输出。最后,final_score
的mean
:输出:
You could use
rank
method to get the ranks. Then useagg
to get the output as lists for columnrank_list
. Finally,mean
forfinal_score
:Output: