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 select rows by multiple conditions on columns

I would like to reduce my code. So instead of 2 lines I would like to select rows by 3 conditions on 2 columns.
My DataFrame contains Country’s population between 2000 and 2018 by granularity (Total, Female, Male, Urban, Rural)

    Zone        Granularity Year    Value
0   Afghanistan     Total   2000    20779.953
1   Afghanistan     Male    2000    10689.508
2   Afghanistan     Female  2000    10090.449
3   Afghanistan     Rural   2000    15657.474
4   Afghanistan     Urban   2000    4436.282
20909 Zimbabwe      Total   2018    14438.802
20910 Zimbabwe      Male    2018    6879.119
20911 Zimbabwe      Female  2018    7559.693
20912 Zimbabwe      Rural   2018    11465.748
20913 Zimbabwe      Urban   2018    5447.513

I would like all rows of the Year 2017 with granularity Total AND Urban.
I tried something like this below but not working but each condition working well in separate code.

df.loc[(df['Granularity'].isin(['Total', 'Urban'])) & (df['Year'] == '2017')]

Thanks for tips to help

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 :

Very likely, you’re using the wrong type for the year. I imagine these are integers.

You should try:

df.loc[(df['Granularity'].isin(['Total', 'Urban'])) & df['Year'].eq(2017)]

output (for the Year 2018 as 2017 is missing from the provided data):

           Zone Granularity  Year      Value
20909  Zimbabwe       Total  2018  14438.802
20913  Zimbabwe       Urban  2018   5447.513
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