Reputation: 1294
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.
Upvotes: 5
Views: 16676
Reputation: 30920
Also can use lambda function
df.groupby('Month').agg(lambda x: (x=='X').sum())
or
df.groupby('Month').Status.agg(lambda x: (x=='X').sum())
Upvotes: 7
Reputation: 25249
A short way
(df.Status == 'X').groupby(df.Month).sum()
A long way
df.where(df.Status == 'X').groupby('Month').Status.count()
Upvotes: 6
Reputation: 8033
You an do df.loc[df.Status=='X'].groupby(['Month']).agg({'Status' : ['count']})
Upvotes: 1