gpt4 book ai didi

python - Pandas :有条件的groupby

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:30 25 4
gpt4 key购买 nike

我有数据框:

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,我想删除这个类别。我不知道,我怎么能在那里写这个条件。

最佳答案

作为EdChum commented , 你可以使用 filter :

您还可以通过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

关于python - Pandas :有条件的groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39634175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com