Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing a condition while calculating using numpy array

Tags:

python

numpy

Below is a short piece of code that for some reason keeps generating the following value error message: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

import numpy as np
p=np.array([1,2,3])
q=np.array([4,5,5])

while p + q==7:
        try:
            assert p.any()
            assert q.any()
        except AssertionError:
            print('(p + q)<=6')
        print  (p + q)

I have tried both p.any and p.all, still getting the same error message. Any suggestions? Thanks.

like image 916
Tiger1 Avatar asked Mar 03 '26 14:03

Tiger1


1 Answers

Your problem is that p and q have three elements each, so p + q == 7 will also have three elements. For the while loop, you need something that can be interpreted as True or False - the error is telling you that three elements can't be interpreted as True or False without more information: it's ambiguous. If you want all of the elements to be equal to 7, use

while np.all(p + q == 7):

if you want any of them to be equal, use

while np.any(p + q == 7):
like image 85
chthonicdaemon Avatar answered Mar 05 '26 02:03

chthonicdaemon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!