Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas use and operator in LOC function

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?

like image 458
jxn Avatar asked Jan 17 '17 07:01

jxn


People also ask

What is the & operator in Python pandas?

Use the & operator to index a pandas DataFrameIndex multiple columns of a DataFrame against a conditional to convert each element to a boolean value. Use the & operator to take an element-wise and of the resulting DataFrames to return a boolean DataFrame to be used for indexing.

Can you use and in pandas?

It's important to realize that you cannot use any of the Python logical operators ( and , or or not ) on pandas. Series or pandas. DataFrame s (similarly you cannot use them on numpy. array s with more than one element).

Can I use ILOC and loc together?

In this case, loc and iloc are interchangeable when selecting via a single value or a list of values. Note that loc and iloc will return different results when selecting via slice and conditions.

Is ILOC () and loc () functions are same?

loc and iloc are interchangeable when the labels of the DataFrame are 0-based integers.


2 Answers

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']
like image 178
jezrael Avatar answered Sep 23 '22 23:09

jezrael


Using query

df.query('ratings < 3 & business_id == @id').review_text.tolist()

["'very bad'", "'passable'"]
like image 43
piRSquared Avatar answered Sep 25 '22 23:09

piRSquared