Home >Backend Development >Python Tutorial >How to Use Pandas' `.isin()` for DataFrame Filtering: IN and NOT IN Operations?
Using Pandas' .isin() for DataFrame Filtering
In SQL, the IN and NOT IN operators allow you to filter data based on a list of values. Pandas' DataFrame provides a convenient method, .isin(), that enables similar functionality.
How to Use .isin()
To use .isin():
Example Usage
Consider the following DataFrame:
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
And a list of countries to keep:
countries_to_keep = ['UK', 'China']
To filter the DataFrame using the equivalent of SQL's IN:
df[df.country.isin(countries_to_keep)]
This will return:
country 1 UK 3 China
For the equivalent of SQL's NOT IN:
df[~df.country.isin(countries_to_keep)]
This will return:
country 0 US 2 Germany
This method avoids the use of clumsy kludges and provides a straightforward way to filter DataFrames based on a list of values.
The above is the detailed content of How to Use Pandas' `.isin()` for DataFrame Filtering: IN and NOT IN Operations?. For more information, please follow other related articles on the PHP Chinese website!