Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas groupby and agg by condition

df.groupby(['Month']).agg({'Status' : ['count']})

The line above groups the dataframe by Month and counts the number of Status for each month. Is there a way to only get a count where Status=X? Something like the incorrect code below:

df.groupby(['Month']).agg({'Status' == 'X' : ['count']})

Essentially, I want a count of how many Status are X for each month.

like image 806
novice Avatar asked Nov 07 '19 01:11

novice


2 Answers

A short way

(df.Status == 'X').groupby(df.Month).sum()

A long way

df.where(df.Status == 'X').groupby('Month').Status.count()
like image 155
Andy L. Avatar answered Nov 09 '22 23:11

Andy L.


Let us do something different

pd.crosstab(df.Month,df.Status)['X']
like image 27
BENY Avatar answered Nov 09 '22 21:11

BENY