小编典典

如何使用 SQL 中的“in”和“not in”过滤 Pandas 数据帧

all

如何实现 SQLIN和的等价物NOT IN

我有一个包含所需值的列表。这是场景:

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

# pseudo-code:
df[df['country'] not in countries_to_keep]

我目前的做法如下:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})

# IN
df.merge(df2, how='inner', on='country')

# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]

但这似乎是一个可怕的组合。任何人都可以改进它吗?


阅读 157

收藏
2022-03-03

共1个答案

小编典典

您可以使用pd.Series.isin.

对于“IN”使用:something.isin(somewhere)

或者对于“不在”:~something.isin(somewhere)

作为一个工作示例:

import pandas as pd

>>> 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
>>> df[df.country.isin(countries_to_keep)]
  country
1        UK
3     China
>>> df[~df.country.isin(countries_to_keep)]
  country
0        US
2   Germany
2022-03-03