选择groupby中的前3个元素 [英] Selecting top 3 elements within groupby

查看:120
本文介绍了选择groupby中的前3个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下按表分组的熊猫,我如何才能在每个CPUCore中获得Offline_RentetionAge的前3个index,并保持表的结构?

Given the following pandas group by table, how could I get the top 3 index for Offline_RentetionAge within each CPUCore, and keep the structure of the table?

对于上述结果,应该是

   CPUCore  Offline_RetetionAge  index
0        i7     183                4184
1               7                  1981
2               30                  471
3        i5     ..                ...

推荐答案

您可以使用

You can use GroupBy.head if values in index column are sorted:

df = df.groupby(level=0).head(3)

示例:

df = pd.DataFrame({'CPUCore':['i7'] * 4 + ['i5'] * 4,
                    'Offline_RetetionAge':['100','1','12','120','15','10','20','3'],
                   'index':[11,16,5,4,30,18,2,1]})
       .set_index(['CPUCore','Offline_RetetionAge'])

print (df)
                             index
CPUCore Offline_RetetionAge       
i7      100                     11
        1                       16
        12                       5
        120                      4
i5      15                      30
        10                      18
        20                       2
        3                        1

df = df.groupby(level=0).head(3)
print (df)
                             index
CPUCore Offline_RetetionAge       
i7      100                     11
        1                       16
        12                       5
i5      15                      30
        10                      18
        20                       2

这篇关于选择groupby中的前3个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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