Search code examples
pythonpandasfiltergroup-bycounting

Can you filter with in a groupby function in pandas?


Hello Stackoverflow Community, I was wondering if it is possible to filter with in a groupby function in pandas and the reason why is because I want to find out for each gender what is the total number of mobile users. In my dataset we have a Boolean column named mobile where if a customer is mobile it would be considered True and False if not. We a Gender column which is a string data type which lets us know the gender of a customer such as male, female and other. I also have a customer column which is a string data type also and what I am trying to do is get the total number of mobile customers for each gender. This is what my code looked like to get what I am trying to get:

df.groupby('gender')[df['mobile'] == True]['customer'].count()

But this piece of code didn't work. Could someone please help me figure this out?


Solution

  • No, you can't, filter before the groupby:

    df[df['mobile'] == True].groupby('gender')['customer'].count()