LOC 函数中的 Pandas 使用和运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41691081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas use and operator in LOC function
提问by jxn
i want to have 2 conditions in the loc
function but the &&
or and
operators dont seem to work.:
我想在loc
函数中有 2 个条件,但&&
orand
运算符似乎不起作用。:
df:
df:
business_id ratings review_text
xyz 2 'very bad'
xyz 1 'passable'
xyz 3 'okay'
abc 2 'so so'
mycode:
i am trying to gather all review_text
whose ratings are < 3
and have id = xyz
into a list
mycode的:我试图收集所有review_text
它的收视率< 3
,并有id = xyz
到一个列表
id = 'xyz'
mylist = df.loc[df['ratings'] < 3 and df[business_id] ==id,'review_text'].values.tolist()
i should get:
我应该得到:
['very bad','passable']
This code doesnt work and i get the error:
此代码不起作用,我收到错误消息:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
how do i use the and
operator correctly here?
我如何and
在这里正确使用运算符?
采纳答案by jezrael
You need &
for and
logical operator, because need element-wise and
, see boolean indexing:
你需要&
的and
逻辑运算符,因为需要逐元素and
,见布尔索引:
id = 'xyz'
mylist=df.loc[(df['ratings'] < 3) & (df['business_id'] == id),'review_text'].values.tolist()
print (mylist)
['very bad', 'passable']
回答by piRSquared
Using query
使用 query
df.query('ratings < 3 & business_id == @id').review_text.tolist()
["'very bad'", "'passable'"]
回答by B. Kanani
use ~ for not logical operation
使用 ~ 进行非逻辑操作
For example:
例如:
train.loc[(train['MiscVal'] == 0) & (~train['MiscFeature'].isna())]