0

I was checking out the answer to this question and had a quick follow-up question. The answer says that in case of multiple conditions parentheses are required since operator "&" is more binding than comparison operators:

df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]

And missing parentheses here will result in 'value ambiguous' error.

Looking at operator precedence rules I noticed that and is less binding than comparison operators. In this case can the same be re-written like this?

df.loc[df['column_name'] >= A and df['column_name'] <= B]
James Mchugh
  • 994
  • 8
  • 26
NotAName
  • 3,821
  • 2
  • 29
  • 44
  • 2
    It cannot be used in this case since `and` will attempt to treat the operands as `bool`s, causing their magic method `__bool__` to run. It will return the error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().". – James Mchugh Nov 27 '19 at 23:54
  • 2
    `&` operator is not an equivalent to `and`. `&` is a bit-wise operator. Maybe you are thinking of `&&` (boolean and) in other languages, python does not have this. Or rather, it has `and` – Hymns For Disco Nov 27 '19 at 23:55
  • Yeah, this is where I got confused. Now I noticed that one is boolean and the other is bitwise. Good to know. Explains a lot of issues I've been having. – NotAName Nov 27 '19 at 23:56
  • @HymnsForDisco While `&` is normally the bitwise operator, it is overloaded in DataFrames and Series to do element-wise operations, either bitwise or logical operations depending on the context. In the case of `bool`s, it does the logical and operation. – James Mchugh Nov 27 '19 at 23:58

0 Answers0