Der Grund für die Ausnahme ist, dass andimplizit aufgerufen wird bool. Zuerst auf dem linken Operanden und (wenn der linke Operand ist True) dann auf dem rechten Operanden. Ist x and yalso gleichbedeutend mit bool(x) and bool(y).
Das boolon a numpy.ndarray(wenn es mehr als ein Element enthält) löst jedoch die Ausnahme aus, die Sie gesehen haben:
>>> 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()
Der bool()Anruf ist implizit in and, sondern auch in if, while, or, so dass jede der folgenden Beispiele wird auch fehlschlagen:
>>> 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()
Es gibt mehr Funktionen und Anweisungen in Python, die boolAufrufe verbergen. Dies ist beispielsweise 2 < x < 10nur eine andere Schreibweise 2 < x and x < 10. Und der andwird anrufen bool: bool(2 < x) and bool(x < 10).
Das elementweise Äquivalent für andwäre die np.logical_andFunktion, ähnlich wie Sie es np.logical_orals Äquivalent für verwenden könnten or.
Für boolean Arrays - und Vergleiche wie <, <=, ==, !=, >=und >auf NumPy Arrays zurückgeben boolean NumPy Arrays - auch die können elementweise bitweise Funktionen (und Betreiber): np.bitwise_and( &Betreiber)
>>> 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)
und bitwise_or( |Betreiber):
>>> 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)
Eine vollständige Liste der logischen und binären Funktionen finden Sie in der NumPy-Dokumentation: