Pandas怎样实现SQL一样的in和not in 语法

语法

直接使用 pd.Series.isin

# in
something.isin(somewhere)

# "NOT IN": 
~something.isin(somewhere)

举例

>>> df
    country
0        US
1        UK
2   Germany
3     China

>>> countries_to_keep
['UK', 'China']

>>> df.country.isin(countries_to_keep)
0    False
1     True
2    False
3     True
Name: country, dtype: bool

# 实现isin
>>> df[df.country.isin(countries_to_keep)]
    country
1        UK
3     China

# 实现 not in
>>> df[~df.country.isin(countries_to_keep)]
    country
0        US
2   Germany

参考资料:

https://stackoverflow.com/questions/19960077/how-to-filter-pandas-dataframe-using-in-and-not-in-like-in-sql

Leave a Comment