2017-04-21 120 views
2

我有一个数据帧,看起来像:Python的大熊猫GROUPBY多计数

id   email  domain   created_at company 
0 1 [email protected] old.com 2017-01-21 18:19:00 company_a 
1 2 [email protected] new.com 2017-01-22 01:19:00 company_b 
2 3 [email protected] nadda.com 2017-01-22 01:19:00 no_company 

我需要总结的年,月的数据,如果公司有一个值不匹配“no_company”:

所需的输出:

year  month  company  count         
2017  1   has_company 2 
         no_company  1 

下的伟大工程,但给我的公司列中的每个值的计数;

new_df = test_df['created_at'].groupby([test_df.created_at.dt.year, test_df.created_at.dt.month, test_df.company]).agg('count') 
print(new_df) 

结果:

year  month  company          
2017  1   company_a  1 
         company_b  1 
         no_company  1 

回答

4

映射一个新的系列has_company/no_company然后groupby

c = df.company.map(lambda x: x if x == 'no_company' else 'has_company') 
y = df.created_at.dt.year.rename('year') 
m = df.created_at.dt.month.rename('month') 

df.groupby([y, m, c]).size() 

year month company  
2017 1  has_company 2 
      no_company  1 
dtype: int64 
+0

PERFECTO!谢谢! – FunnyChef