Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, you can’t, filter before the groupby:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading