samedi 3 octobre 2020

Need to compare two arrays elements inside a for loop in Python 3 and getting error "The truth value of an array ..."

I have a numpy array in the form:

y_sol = 
[[0. 0. 1.]
 [0. 0. 1.]
 [0. 0. 1.]
 ...
 [1. 0. 0.]
 [0. 1. 0.]
 [1. 0. 0.]]

and I need to translate it for a categorical string value using correlations given by a list of tuples:

transf_codes = [('Alert', [1., 0., 0.]),     
                ('Neutral', [0., 1., 0.]),     
                ('Urgent', [0., 0., 1.])]   

Note that I haven't used a dictionary here to avoid a complication to search for keys having the values as the search input.

Anyhow, I've tried the following code to have the job done:

for i in np.arange(len(y_sol)-1): 
    for j in np.arange(3):
        if np.equal(transf_codes[j][1], y_sol[i].all()):  # <-error line 
            y_categ[i] = transf_codes[j][0] 

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

In the "if" line above, the more natural form >>> transf_codes[j][1] == y_sol[i] <<<, with or without .all() or .any(), raises the same error.

What is the righ and best approach to compare element-wise of arrays, lists, etc. in an if-statement?

Many thanks in advance.

Aucun commentaire:

Enregistrer un commentaire