8

I understand the pandas docs explain that this is the convention, but I was wondering why?

For example:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4), index=list('abcdef'), columns=list('ABCD'))
print(df[(df.A < .5) | (df.B > .5)])
print(df[(df.A < .5) or (df.B > .5)])   

Returns the following:

          A         B         C         D
a -0.284669 -0.277413  2.524311 -1.386008
b -0.190307  0.325620 -0.367727  0.347600
c -0.763290 -0.108921 -0.467167  1.387327
d -0.241815 -0.869941 -0.756848 -0.335477
e -1.583691 -0.236361 -1.007421  0.298171
f -3.173293  0.521770 -0.326190  1.604712
Traceback (most recent call last):
  File "C:\test.py", line 64, in <module>
    print(df[(df.A < .5) or (df.B > .5)])   
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Ben Southgate
  • 3,388
  • 3
  • 22
  • 31

1 Answers1

17

Because & and | are overridable (customizable). You can write the code that drives the operators for any class.

The logic operators and and or, on the other hand, have standard behavior that cannot be modified.

See here for the relevant documentation.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • I guess related question/answer for the second part: http://stackoverflow.com/questions/471546/any-way-to-override-the-and-operator-in-python – Andy Hayden Dec 19 '13 at 21:05
  • because each result is a a list of true/false, which correlates closely to bits, and so a bitwise operator absolutely makes sense (in addition to the answer given here... plus how did you make your name do that(@answerer)?) – Joran Beasley Dec 19 '13 at 21:34
  • It's just some unicode and some normal characters n -> u, m -> w, d -> p – salezica Dec 19 '13 at 23:11
  • Back in the BBS days, we used to write that as `umop apsidn`, just using good ol' ASCII. Close enough... – kindall Dec 20 '13 at 16:43
  • 1
    Also: the *reason* that `and` and `or` aren't overrideable is because they short-circuit. That is, the second argument might not even be evaluated. – kindall Dec 20 '13 at 16:44