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

后端 未结 3 677
情歌与酒
情歌与酒 2020-12-05 15:27

I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via assert(). This would throw a ValueError that I don\

3条回答
  •  鱼传尺愫
    2020-12-05 16:08

    The error message explains it pretty well:

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

    What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

    (1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

    (2) True, because at least one element is True;

    (3) False, because not all elements are True;

    and that's not even considering the complexity of the N-d case.

    So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

    >>> v = np.array([1,2,3]) == np.array([1,2,4])
    >>> v
    array([ True,  True, False], dtype=bool)
    >>> v.any()
    True
    >>> v.all()
    False
    

    and you might want to consider np.allclose if you're comparing arrays of floats:

    >>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
    True
    

提交回复
热议问题