PhishFood
PhishFood

Reputation: 71

How to filter and groupby in python

I have a data set (made up the below as an example) and I am trying to group and filter at the same time. I want to groupby the occupation and then filter the Sex for just males. I am also working in pandas.

Occupation             Age    Sex
Accountant              23     Female
Doctor                  33     Male
Accountant              43     Male
Doctor                  28     Female

I'd like the final result to look something like this:

Occupation    Sex
Accountant     1
Doctor         1

So far I have come up with the below but it doesn't filter males for sex

data.groupby(['occupation'])[['sex']].count()    

Thank you.

Upvotes: 2

Views: 1579

Answers (1)

piRSquared
piRSquared

Reputation: 294258

Use query prior to groupby

data.query('Sex == "Male"').groupby('Occupation').Sex.size().reset_index()

Upvotes: 2

Related Questions