Thursday, June 20, 2013

"The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

I see the error in the post title a lot when I'm trying to check values in arrays. I'm finally going to really figure out what it means by a.any() and a.all()!

I have a four element array, and I want to know if it has any 1's in it:

a = array([2, 3, 3, 2])
a.any()

This will return True, because it is checking to see if any of the elements in a are greater than zero. This is not helpful. We need to define an intermediate matrix that has truth values for the condition we want to test.

a = array([2, 3, 3, 2])
b =  a==0
b.any()

works!

Or,

a = array([2, 3, 3, 2])
any(a>0)

works!

a.all()  and all() should work in the same way, but be testing for ALL the values to be true.



No comments:

Post a Comment