我有一个熊猫数据框,我只希望每个设备的前10个count
。我想一种简单的方法是创建一个名为rank
的新列,然后删除等级大于10的所有内容。这是数据:
p_dt device namestr count
0 2020-04-29 windows m_outcome1 207209
1 2020-04-29 windows m_outcome2 56599
2 2020-04-29 windows m_outcome3 2880
3 2020-04-29 windows m_outcome4 2879
4 2020-04-29 windows m_outcome5 2879
... ... ... ... ...
50204 2020-04-29 web gateway wg_outcome1 2
50205 2020-04-29 web gateway wg_outcome2 2
50206 2020-04-29 web gateway wg_outcome3 1
50207 2020-04-29 web gateway wg_outcome4 1
50208 2020-04-29 web gateway wg_outcome5 1
我遇到的问题是,如果count
具有每个device
相同的多个数字,那么排名将重复多次。
df.groupby('deviceproduct', sort=False)['count'].rank(ascending=False)
0 1.0
1 2.0
2 3.0
3 5.0
4 5.0
...
50204 20.5
50205 20.5
50206 23.0
50207 23.0
50208 23.0
当我真正想要相同的数据时:
0 1.0
1 2.0
2 3.0
3 5.0
4 6.0
...
有没有办法做到这一点?
您应该考虑在method=first
方法中使用rank
。
df.groupby('deviceproduct', sort=False)['count'].rank(ascending=False, method='first')
这应该给您每个组唯一的排名。