Home > Backend Development > Python Tutorial > How to Use Pandas' `.isin()` for DataFrame Filtering: IN and NOT IN Operations?

How to Use Pandas' `.isin()` for DataFrame Filtering: IN and NOT IN Operations?

Patricia Arquette
Release: 2024-12-25 06:12:17
Original
978 people have browsed it

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():

  • For IN: Use something.isin(somewhere)
  • For NOT IN: Use ~something.isin(somewhere)

Example Usage

Consider the following DataFrame:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
Copy after login

And a list of countries to keep:

countries_to_keep = ['UK', 'China']
Copy after login

To filter the DataFrame using the equivalent of SQL's IN:

df[df.country.isin(countries_to_keep)]
Copy after login

This will return:

    country
1        UK
3     China
Copy after login

For the equivalent of SQL's NOT IN:

df[~df.country.isin(countries_to_keep)]
Copy after login

This will return:

    country
0        US
2   Germany
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template