如何实现SQL语言的IN
和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'])]
但这看起来像是一个可怕的杂技。有人能改进它吗?
https://stackoverflow.com/questions/19960077
复制相似问题