[Numpy-discussion] Truth value of an array

Joe Harrington jh@physics.ucf....
Fri Apr 18 15:33:34 CDT 2008

```For that matter, is there a reason logical operations don't work on
arrays other than booleans?  What about:

import numpy

x = numpy.ones((10), dtype='Bool')
y = numpy.ones((10), dtype='Bool')

y[6] = False
z = x and y   # logical AND: this one fails with an error about arrays
---------------------------------------------------------------------------
<type 'exceptions.ValueError'>            Traceback (most recent call last)

/home/jh/<ipython console> in <module>()

<type 'exceptions.ValueError'>: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
---------------------------------------------------------------------------
z = x & y     # bitwise AND: this one succeeds
print z
[ True  True  True  True  True  True False  True  True  True]

But, both operators should return the same result, since booleans have
one bit.  Where this really matters is ANDing ints:

x = numpy.ones((10), dtype='uint8')
y = numpy.ones((10), dtype='uint8')

y[6] = 2      # still True this time: http://docs.python.org/ref/Booleans.html
z = x and y   # logical AND: this one fails with an error about arrays
---------------------------------------------------------------------------
<type 'exceptions.ValueError'>            Traceback (most recent call last)

/home/jh/<ipython console> in <module>()

<type 'exceptions.ValueError'>: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
---------------------------------------------------------------------------
z = x & y     # bitwise AND: this one succeeds...but it isn't the AND I want!
print z
[1 1 1 1 1 1 0 1 1 1]  # the AND I want makes this array all True

Here, both x and y are completely True, but you can't trivially do a
logical AND, and the bitwise & isn't the one you want.  You have to
cast to boolean manually and do the logical instead.

Can this be fixed or is there a reason for the exception?

--jh--
```