我怎样才能实现SQL的的等价物IN和NOT IN?
我有一个包含所需值的列表.这是场景:
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']
# pseudo-code:
df[df['countries'] not in countries]
Run Code Online (Sandbox Code Playgroud)
我目前的做法如下:
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'])]
Run Code Online (Sandbox Code Playgroud)
但这似乎是一个可怕的kludge.任何人都可以改进吗?
这工作(使用Pandas 12 dev)
table2=table[table['SUBDIVISION'] =='INVERNESS']
Run Code Online (Sandbox Code Playgroud)
然后我意识到我需要使用"开头"来选择字段因为我错过了一堆.所以按照我可以遵循的熊猫文档,我试过了
criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS'))
table2 = table[criteria]
Run Code Online (Sandbox Code Playgroud)
并得到了AttributeError:'float'对象没有属性'startswith'
所以我尝试了一种具有相同结果的替代语法
table[[x.startswith('INVERNESS') for x in table['SUBDIVISION']]]
Run Code Online (Sandbox Code Playgroud)
参考http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing 第4部分:系列的列表推导和映射方法也可用于生成更复杂的标准:
我错过了什么?