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

Pandas – Count column categorical value based on another column categorical value

I’m new to python and pandas. I have a data set with the columns age, sex, bmi, children, smoker, region, charges. I want to write a query to count all the smokers that answered "yes" based on their region. the regions can only be northwest, northeast, southwest, southeast.

I have tried several groupby and series commands but i’m not getting it. Can anyone help? Thanks in advance

I’ve tried:

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

data.groupby('Region').count()
data.groupby('Region').apply(lambda g: pd.Series(g['Smoker'].str.contains("y").count()))
data['Smoker'].value_counts().reindex(['Region'])

None of them worked.

>Solution :

You can go for this :

df.groupby(['region', 'smoker']).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