Il motivo dell'eccezione è che andchiama implicitamente bool. Prima sull'operando di sinistra e (se l'operando di sinistra è True) poi sull'operando di destra. Quindi x and yè equivalente a bool(x) and bool(y).
Tuttavia, l' boolon a numpy.ndarray(se contiene più di un elemento) genererà l'eccezione che hai visto:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
La bool()chiamata è in implicita and, ma anche in if, while, or, in modo che qualsiasi dei seguenti esempi fallirà anche:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Ci sono più funzioni e istruzioni in Python che nascondono le boolchiamate, ad esempio 2 < x < 10è solo un altro modo di scrivere 2 < x and x < 10. E la andchiamerà bool: bool(2 < x) and bool(x < 10).
L' equivalente dal punto di vista dell'elementoand sarebbe la np.logical_andfunzione, allo stesso modo si potrebbe usare np.logical_orcome equivalente per or.
Per gli array booleani - e confronti piace <, <=, ==, !=, >=e >sul NumPy array restituiscono array NumPy booleane - è anche possibile utilizzare i elemento-saggio bit a bit funzioni (e operatori): np.bitwise_and( &operatore)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
e bitwise_or( |operatore):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
Un elenco completo di funzioni logiche e binarie è disponibile nella documentazione di NumPy: