Reputation: 673
A DataFrame is called c, and it has a column called price in which I want to know the rows with price equal to 2 or 3. And the code works here
c[(c['price'] == 2) | (c['price'] == 3)]
But doesn't work here:
c[c['price'] == 2 | c['price'] == 3]
and raises an exception:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
The only difference is in the second line of code, there's no parenthesis '()' wrapped to the operation. So why the parenthesis is so important?
Thank you very much!
Upvotes: 2
Views: 1043
Reputation: 62463
|
for or
, &
for and
, and ~
for not
. These must be grouped by using parentheses, since by default Python will evaluate an expression such as df['A'] > 2 & df['B'] < 3
as df['A'] > (2 & df['B']) < 3
, while the desired evaluation order is (df['A > 2) & (df['B'] < 3)
Upvotes: 7