Categories
Python Answers

How to filter Python Pandas dataframe using ‘in’ and ‘not in’ like in SQL?

Spread the love

To filter Python Pandas dataframe using ‘in’ and ‘not in’ like in SQL, we call the isin method.

For instance, we write

df[df.country.isin(countries_to_keep)]

to call df.country.isin to get the rows that has the country column set to the values in the countries_to_keep list.

We can negate isin with ~, so we can write

df[~df.country.isin(countries_to_keep)]

to call df.country.isin to get the rows that has the country column that aren’t set to the values in the countries_to_keep list.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.