大 pandas 损失最大的一栏 [英] pandas nlargest lost one column
本文介绍了大 pandas 损失最大的一栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数据集:
Id query count
001 abc 20
001 bcd 30
001 ccd 100
002 ace 13
002 ahhd 30
002 ahe 28
我想根据计数找到每个ID的Top2查询.所以我想看看:
I want to find the Top2 query for each Id, based on the count. So I want to see:
Id query count
001 ccd 100
001 bcd 30
002 ahhd 30
002 ahe 28
我尝试了这两行代码:
df.groupby('Id')['count'].nlargest(2)
,结果中丢失了查询"列,这不是我想要的.那么如何在我的结果中保持查询.
ID计数
df.groupby('Id')['count'].nlargest(2)
, the "query" column is lost in the result, which is not what I wanted. So how to keep query in my result.
Id count
001 100
001 30
002 30
002 28
推荐答案
使用 set_index
缺少的列:
Use set_index
of missing column(s):
df = df.set_index('query').groupby('Id')['count'].nlargest(2).reset_index()
print (df)
Id query count
0 001 ccd 100
1 001 bcd 30
2 002 ahhd 30
3 002 ahe 28
这篇关于大 pandas 损失最大的一栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文