如何在 Pandas Python 中按 id 对行进行排名 [英] How to rank rows by id in Pandas Python

查看:68
本文介绍了如何在 Pandas Python 中按 id 对行进行排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a Dataframe like this:

id     points1    points2
1        44          53
1        76          34
1        63          66
2        23          34 
2        44          56

我想要这样的输出:

id     points1    points2     points1_rank     points2_rank
1        44          53            3                2
1        76          34            1                3
1        63          66            2                1
2        23          79            2                1
2        44          56            1                2

基本上,我想groupby('id'),并找到具有相同id的每一列的排名.

Basically, I want to groupby('id'), and find the rank of each column with same id.

我试过了:

features = ["points1","points2"]
df = pd.merge(df, df.groupby('id')[features].rank().reset_index(), suffixes=["", "_rank"], how='left', on=['id'])

但是我得到 keyerror 'id'

推荐答案

rank

df.join(df.groupby('id')['points1', 'points2'].rank(ascending=False).astype(int).add_suffix('_rank'))


+---+----+---------+---------+--------------+--------------+
|   | id | points1 | points2 | points1_rank | points2_rank |
+---+----+---------+---------+--------------+--------------+
| 0 |  1 |      44 |      53 |            3 |            2 |
| 1 |  1 |      76 |      34 |            1 |            3 |
| 2 |  1 |      63 |      66 |            2 |            1 |
| 3 |  2 |      23 |      34 |            2 |            2 |
| 4 |  2 |      44 |      56 |            1 |            1 |
+---+----+---------+---------+--------------+--------------+

这篇关于如何在 Pandas Python 中按 id 对行进行排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆