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

新手上路,请多包涵

如何实现 SQL 的 INNOT 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'])]

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

原文由 LondonRob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 568
2 个回答

您可以使用 pd.Series.isin

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

或者对于“不在”: ~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
>>> df[df.country.isin(countries_to_keep)]
    country
1        UK
3     China
>>> df[~df.country.isin(countries_to_keep)]
    country
0        US
2   Germany

原文由 DSM 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 .query() 方法的替代解决方案:

 In [5]: df.query("countries in @countries_to_keep")
Out[5]:
  countries
1        UK
3     China

In [6]: df.query("countries not in @countries_to_keep")
Out[6]:
  countries
0        US
2   Germany

原文由 MaxU - stop genocide of UA 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题