Dwa
Dwa

Reputation: 673

pandas.DataFrame why use parenthesis to wrap operations to make bitwise comparison

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

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62463

  • As per Pandas: Boolean indexing
    • Another common operation is the use of boolean vectors to filter the data. The operators are: | 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

Related Questions