WalksB
WalksB

Reputation: 519

Why doesn't Pandas use default python 'and' and 'or'?

I can't understand why Pandas doesn't overload/allow the use of the "and" and "or" operators built in to python when comparing dataframes

import pandas as pd                                                     

In [4]: d = {'a':[True,False], 'b':[False,False]}                               

In [5]: x = pd.DataFrame(d)                                                     

In [6]: x['a'] & x['b']                                                         
Out[6]: 
0    False
1    False
dtype: bool

In [7]: x['a'] and x['b']                                                       
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-0ee6588ad92b> in <module>
----> 1 x['a'] and x['b']

/usr/local/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In [8]:               

Upvotes: 1

Views: 143

Answers (1)

user2357112
user2357112

Reputation: 280973

It can't. You can't overload those. Overloading would interact poorly with short-circuit semantics, so Python doesn't allow it.

Upvotes: 3

Related Questions