I have a dataframe like this:
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
降序为每行分配一个总体排名。
即,我希望结果看起来像这样:
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中使用group by和ranking实现这个功能?看起来在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])
我该如何做到这一点?我知道一个不太正规的方法是先在整个数据帧上使用sort_values
,然后再使用groupby
,但是当我只想在每个组中排序几行时,对整个数据帧的行进行排序似乎太昂贵了。