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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *