Search code examples
pythonfor-loopif-statementvalueerror

ValueError in For Loop's If Condition with two boolean arrays


I'm running a For-Loop with an If Statement including two boolean Arrays to create a new array.

I already tried all Solutions I could find on StackOverflow, exchanging the & with Logical_and or bitwise_and, also using the suggested a.any() & a.all() methods, I still get the same ValueError.

y_valid = [True, False, True, False, False, True]
y_pred = [False, False, True, True, False, False]

for i in (y_valid, y_pred):
    CM = []
    if (y_valid[i] == False) & (y_pred[i] == False):
        CM == 0
    elif (y_valid[i] == False) & (y_pred[i] == True):
        CM == 1
    elif (y_valid[i] == True) & (y_pred[i] == False):
        CM == 2
    elif (y_valid[i] == True) & (y_pred[i] == True):
        CM == 3

I expect to get an array CM including numerals from 0-3

My Output:

ValueError                                Traceback (most recent call last)
<ipython-input-107-259ac7895185> in <module>
      1 for i in (y_valid, y_pred):
      2     CM = []
----> 3     if (y_valid[i] == False) & (y_pred[i] == False):
      4         CM == 0
      5     elif (y_valid[i] == False) & (y_pred[i] == True):

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

Solution

  • If I understand correctly you want the following:

    y_valid = [True, False, True, False, False, True]
    y_pred = [False, False, True, True, False, False]
    
    # Move this out of the loop so you do not reset it every time!
    CM = []
    
    # To make i integer (as required for it to be list index) 
    # use range and len.
    for i in range(len(y_valid)):
        # Dropping comparisons with True/False values since 
        # the following would be the same. Also note that `&` is 
        # a bitwise operator in python while `and` is boolean
        if not y_valid[i] and not y_pred[i]:
            # In every iteration we are now appending to the same CM list
            CM.append(0)
        elif not y_valid[i] and y_pred[i]:
            CM.append(1)
        elif y_valid[i] and not y_pred[i]:
            CM.append(2)
        elif y_valid[i] and y_pred[i]:
            CM.append(3)
    
    print(CM)
    

    The output is:

    $ python /tmp/test.py 
    [2, 0, 3, 1, 0, 2]
    

    Checkout the comments in the code for the changes I made to the original one. Let me know if you have questions