gpt4 book ai didi

python - 如何像在 SQL 中一样使用 'in' 和 'not in' 过滤 Pandas 数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:14 27 4
gpt4 key购买 nike

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

但这似乎是一个可怕的拼凑。有人可以改进吗?

最佳答案

您可以使用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

关于python - 如何像在 SQL 中一样使用 'in' 和 'not in' 过滤 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349057/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com