On Sep 21, 2012 4:09 PM, "Bala subramanian" <bala.biophys...@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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to