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.