[SciPy-Dev] Numpy's handling of conditions

Michael Clerx cell at michaelclerx.com
Wed Oct 1 05:01:42 EDT 2014


Hi Everyone,

I'm a bit confused about the way numpy treats conditions and I'm hoping 
you can help.

Starting from this array:

x = np.array(x)
 >>> x
array([1, 2, 3, 2, 1])
 >>> x == 1
array([ True, False, False, False,  True], dtype=bool)

works as expected, but the following is horribly wrong:

 >>> x == 1 + x == 3
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

I can live with that, but why do brackets solve this?

 >>> (x == 1) + (x == 3)
array([ True, False,  True, False,  True], dtype=bool)

Which is the same result as

 >>> (x == 1) | (x == 3)
array([ True, False,  True, False,  True], dtype=bool)

It gets a bit weirder:

 >>> (x == 1) + (x < 3)
array([ True,  True, False,  True,  True], dtype=bool)

but

 >>> True + True
2

Is this the way it's supposed to work? Since it's quite different from 
python's scalar types, perhaps the documentation should mention it more 
clearly (for example, why isn't "or" implemented as a piecewise or).

cheers,
   Michael



More information about the SciPy-Dev mailing list