本文翻译自:How to filter Pandas dataframe using 'in' and 'not in' like in SQL
How can I achieve the equivalents of SQL's IN
and NOT IN
? 如何实现SQL的IN
和NOT IN
的等效项?
I have a list with the required values. 我有一个包含所需值的列表。 Here's the scenario: 这是场景:
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']
# pseudo-code:
df[df['countries'] not in countries]
My current way of doing this is as follows: 我目前的做法如下:
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = pd.DataFrame({'countries':['UK','China'], 'matched':True})
# IN
df.merge(countries,how='inner',on='countries')
# NOT IN
not_in = df.merge(countries,how='left',on='countries')
not_in = not_in[pd.isnull(not_in['matched'])]
But this seems like a horrible kludge. 但这似乎是一个可怕的冲突。 Can anyone improve on it? 有人可以改进吗?
#1楼
参考:https://stackoom.com/question/1LkWj/如何像在SQL中一样使用-in-和-not-in-过滤Pandas数据帧
#2楼
You can use pd.Series.isin
. 您可以使用pd.Series.isin
。
For "IN" use: something.isin(somewhere)
对于“ IN”,请使用: something.isin(somewhere)
Or for "NOT IN": ~something.isin(somewhere)
或对于“ NOT IN”: ~something.isin(somewhere)
As a worked example: 作为一个工作示例:
>>> df
countries
0 US
1 UK
2 Germany
3 China
>>> countries
['UK', 'China']
>>> df.countries.isin(countries)
0 False
1 True
2 False
3 True
Name: countries, dtype: bool
>>> df[df.countries.isin(countries)]
countries
1 UK
3 China
>>> df[~df.countries.isin(countries)]
countries
0 US
2 Germany
#3楼
I've been usually doing generic filtering over rows like this: 我通常对这样的行进行通用过滤:
criterion = lambda row: row['countries'] not in countries
not_in = df[df.apply(criterion, axis=1)]
#4楼
我想过滤出dfbc行,该行的BUSINESS_ID也在dfProfilesBusIds的BUSINESS_ID中
dfbc = dfbc[~dfbc['BUSINESS_ID'].isin(dfProfilesBusIds['BUSINESS_ID'])]
#5楼
Alternative solution that uses .query() method: 使用.query()方法的替代解决方案:
In [5]: df.query("countries in @countries")
Out[5]:
countries
1 UK
3 China
In [6]: df.query("countries not in @countries")
Out[6]:
countries
0 US
2 Germany
#6楼
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']
implement in : 实施于 :
df[df.countries.isin(countries)]
implement not in as in of rest countries: 不在其他国家/地区实施 :
df[df.countries.isin([x for x in np.unique(df.countries) if x not in countries])]