Home > Backend Development > Python Tutorial > How Can I Simulate SQL's IN and NOT IN Operators Using Pandas' isin() Method?

How Can I Simulate SQL's IN and NOT IN Operators Using Pandas' isin() Method?

Barbara Streisand
Release: 2024-12-23 20:08:15
Original
543 people have browsed it

How Can I Simulate SQL's IN and NOT IN Operators Using Pandas' isin() Method?

Simulating SQL's IN/NOT IN with Pandas' isin() Method

In data analysis, it's common to need to filter a DataFrame based on a set of values, akin to SQL's IN and NOT IN operators. Pandas offers a straightforward solution with the isin() method.

The isin() method operates on Pandas Series and tests if each element in the series is contained in a specified list or set. To replicate SQL's IN, simply apply isin(list) to the desired column:

>>> countries_to_keep = ['UK', 'China']
>>> df.country.isin(countries_to_keep)
Copy after login

For NOT IN, use the negation operator (~):

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

The isin() method simplifies data filtering, eliminating the need for cumbersome merge operations as seen in the initial code sample. Its syntax mirrors SQL's IN/NOT IN, making it easy to incorporate into your Pandas workflow.

The above is the detailed content of How Can I Simulate SQL's IN and NOT IN Operators Using Pandas' isin() Method?. 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