pandas :有条件的分组 [英] Pandas: groupby with condition

查看:76
本文介绍了 pandas :有条件的分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据框:

ID,used_at,active_seconds,subdomain,visiting,category
123,2016-02-05 19:39:21,2,yandex.ru,2,Computers
123,2016-02-05 19:43:01,1,mail.yandex.ru,2,Computers
123,2016-02-05 19:43:13,6,mail.yandex.ru,2,Computers
234,2016-02-05 19:46:09,16,avito.ru,2,Automobiles
234,2016-02-05 19:48:36,21,avito.ru,2,Automobiles
345,2016-02-05 19:48:59,58,avito.ru,2,Automobiles
345,2016-02-05 19:51:21,4,avito.ru,2,Automobiles
345,2016-02-05 19:58:55,4,disk.yandex.ru,2,Computers
345,2016-02-05 19:59:21,2,mail.ru,2,Computers
456,2016-02-05 19:59:27,2,mail.ru,2,Computers
456,2016-02-05 20:02:15,18,avito.ru,2,Automobiles
456,2016-02-05 20:04:55,8,avito.ru,2,Automobiles
456,2016-02-05 20:07:21,24,avito.ru,2,Automobiles
567,2016-02-05 20:09:03,58,avito.ru,2,Automobiles
567,2016-02-05 20:10:01,26,avito.ru,2,Automobiles
567,2016-02-05 20:11:51,30,disk.yandex.ru,2,Computers

我需要做

group = df.groupby(['category']).agg({'active_seconds': sum}).rename(columns={'active_seconds': 'count_sec_target'}).reset_index()

但是我想添加与

df.groupby(['category'])['ID'].count()

,并且如果 category 的计数少于 5 ,我想删除此类别.我不知道,我该怎么写这个条件.

and if count for category less than 5, I want to drop this category. I don't know, how can I write this condition there.

推荐答案

作为 EdChum进行了评论,您可以使用 过滤器:

As EdChum commented, you can use filter:

您还可以通过 sum 来简化聚合:

Also you can simplify aggregation by sum:

df = df.groupby(['category']).filter(lambda x: len(x) >= 5)

group = df.groupby(['category'], as_index=False)['active_seconds']
          .sum()
          .rename(columns={'active_seconds': 'count_sec_target'})
print (group)

      category  count_sec_target
0  Automobiles               233
1    Computers                47

具有 reset_index :

df = df.groupby(['category']).filter(lambda x: len(x) >= 5)

group = df.groupby(['category'])['active_seconds'].sum().reset_index(name='count_sec_target')
print (group)
      category  count_sec_target
0  Automobiles               233
1    Computers                47

这篇关于 pandas :有条件的分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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