Skip to content Skip to sidebar Skip to footer

Compare Two Matrix Values

I have a condition and need to compare values. AV is an arary and 53 is a number. Even if I create the array = 53 * len(AV), python has a problem. The truth value of an array with

Solution 1:

There are (at least) three different things you could mean by if AV <= 53:, and they'd all have very different effects. So, numpy was designed not to try to guess what you mean, and instead raise this error to force you to be explicit.

If you want to do something if all values are under 53, you use the all function or method:

if np.all(a<=53):  # or (a<=53).all()

If you want to do something if any values are under 53, you use the any function or method:

if np.any(a<=53):  # or (a<=53).any()

If you want to do something for each value under 53, and you want to do that with a pure-Python loop, you just loop over the bool array:

for i, flag in enumerate(a<=53):
    if flag:

But of course you almost always want to do the looping inside numpy instead:

a[a<=53]

That's just an array with all the values of a that are <= 53.


If you want to understand exactly how this is happening, you can break things into steps. While if a<=53: loops pretty simple, nothing in numpy is quite as simple as it looks. Try this:

>>> a = np.array([0, 50, 100, 50, 0])
>>> a<=53array([True, True, False, True, True])

So a<=53 is actually an array of 5 bools—each one tells you whether the corresponding member of a is <=53.

And if you try to use that as if it were a single bool:

>>> bool(a<=53)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

That's exactly your error.

Post a Comment for "Compare Two Matrix Values"