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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:48:21  来源:igfitidea点击:

Pandas use and operator in LOC function

pythonpandasoperator-keyword

提问by jxn

i want to have 2 conditions in the locfunction but the &&or andoperators 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_textwhose ratings are < 3and have id = xyzinto 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 andoperator correctly here?

我如何and在这里正确使用运算符?

采纳答案by jezrael

You need &for andlogical 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())]