2016-09-22 286 views
1

我有數據幀:熊貓:GROUPBY與條件

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,我想放棄這個類別。 我不知道,我怎麼能在那裏寫這個條件。

+2

沒有類別會但是,你是否在類似於'df.groupby('category')。filter(lambda x:len(x)> = 5)' – EdChum

回答

4

作爲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另一種解決方案:

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 
在您的樣本數據