[Tutor] np array.any() question

Steven D'Aprano steve at pearwood.info
Fri Sep 21 17:25:54 CEST 2012


On 22/09/12 01:07, Bala subramanian 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

This calculates an array of bools, then calls any() on it.

py> a > 7
array([False, False, False, False, False, False], dtype=bool)
py> (a > 7).any()
False


>>>> (a>  4).any()
> True

This also builds an array of bools, then calls any():

py> a > 4
array([False, False, False, False, False,  True], dtype=bool)
py> (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()


This tries to calculate:

(3 < a) and (a < 5)

py> 3 < a
array([False, False, False,  True,  True,  True], dtype=bool)
py> a < 5
array([ True,  True,  True,  True,  True, False], dtype=bool)

but combining them with the "and" operator is ambiguous:

py> (3 < a) and (a < 5)
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()

Since the boolean "and" of the two arrays never gets calculated,
the any method never gets called. You could do:


py> (3 < a).any() and (a < 5).any()
True

which I think does what you want.



-- 
Steven


More information about the Tutor mailing list