[Tutor] np array.any() question

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Sep 21 17:32:52 CEST 2012


On Sep 21, 2012 4:09 PM, "Bala subramanian" <bala.biophysics at gmail.com>
wrote:
>
> Friends,
> May i know why do get a Valuerror if i check any value in a is between
> 3.0 to 5.0 ?
> >>> import numpy as np
> >>> a=np.array([ 2.5,  2.6,  3.0 ,  3.5,  4.0 ,  5.0 ])
> >>> (a > 7).any()
> False
> >>> (a > 4).any()
> True
> >>> (3 < a < 5).any()
> 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()

You need to use ((3 < a) & (a <5)).any()

The problem is not with any(). The problem is that the multiple binary
comparison needs to convert its intermediate results to bool. So (3 < a <
5) is processed as:

(3 < a) and (a < 5)

To process the 'and' operator python needs to know if the first expression
is True. This means calling bool(3 < a). But, since (3 < a) is an array of
booleans it cannot be said to be True or False. This is what gives the
ValueError that you see.

If you use bitwise-and '&' instead of logical-and 'and' it will perform the
and operation separately on each element of each array which is what you
want.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120921/322c37ae/attachment-0001.html>


More information about the Tutor mailing list