我有一个像这样的数据框:
df = pd.DataFrame({'asset_id': [10,10, 10, 20, 20, 20], 'method_id': ['p2','p3','p4', 'p3', 'p1', 'p2'], 'method_rank': [5, 2, 2, 2, 5, 1], 'conf_score': [0.8, 0.6, 0.8, 0.9, 0.7, 0.5]} , columns= ['asset_id', 'method_id','method_rank', 'conf_score'])
它看起来像这样:
asset_id method_id method_rank conf_score
0 10 p2 5 0.8
1 10 p3 2 0.6
2 10 p4 2 0.8
3 20 p3 2 0.9
4 20 p1 5 0.7
5 20 p2 1 0.5
我想按资产 id 对行进行分组,然后根据method_rank
上升和conf_score
下降。
IE。我希望结果看起来像这样:
asset_id method_id method_rank conf_score overall_rank
5 20 p2 1 0.5 1.0
3 20 p3 2 0.9 2.0
2 10 p4 2 0.8 1.0
1 10 p3 2 0.6 2.0
0 10 p2 5 0.8 3.0
4 20 p1 5 0.7 3.0
如何使用 pandas 中的分组依据和排名来做到这一点?看起来在 pandas 中你只能基于一列来完成,就像
df["overall_rank"] = df.groupby('asset_id')['method_rank'].rank("first")
但我想实现类似的目标
df["overall_rank"] = df.groupby('asset_id')[['method_rank', 'conf_score']].rank("first", ascending = [True, False])
我该怎么做呢?我知道一个 hacky 方法是首先使用sort_values
在整个数据帧上然后做groupby
,但是当我只想对每个组中的几行进行排序时,对整个数据帧的行进行排序似乎太昂贵了。