2017-04-21 180 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