Reputation: 8025
i want to have 2 conditions in the loc
function but the &&
or and
operators dont seem to work.:
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
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?
Upvotes: 12
Views: 21600
Reputation: 646
use ~ for not logical operation
For example:
train.loc[(train['MiscVal'] == 0) & (~train['MiscFeature'].isna())]
Upvotes: 2
Reputation: 294328
Using query
df.query('ratings < 3 & business_id == @id').review_text.tolist()
["'very bad'", "'passable'"]
Upvotes: 2
Reputation: 862761
You need &
for and
logical operator, because need element-wise and
, see boolean indexing:
id = 'xyz'
mylist=df.loc[(df['ratings'] < 3) & (df['business_id'] == id),'review_text'].values.tolist()
print (mylist)
['very bad', 'passable']
Upvotes: 17