La razón de la excepción es que andimplícitamente llama bool. Primero en el operando izquierdo y (si el operando izquierdo es True) luego en el operando derecho. Entonces x and yes equivalente a bool(x) and bool(y).
Sin embargo, el boolen un numpy.ndarray(si contiene más de un elemento) arrojará la excepción que ha 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()llamada está en implícita and, sino también en if, while, or, por lo que cualquiera de los siguientes ejemplos también fallará:
>>> 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()
Hay más funciones y declaraciones en Python que ocultan boolllamadas, por ejemplo, 2 < x < 10es solo otra forma de escribir 2 < x and x < 10. Y la andllamarán bool: bool(2 < x) and bool(x < 10).
El equivalente a nivel de elemento para andsería la np.logical_andfunción, de forma similar podría usarlo np.logical_orcomo equivalente para or.
Para las matrices booleanas - y comparaciones como <, <=, ==, !=,>= y >en NumPy matrices devuelven tablas de NumPy booleanos - también puede utilizar los elementos en cuanto a nivel de bit funciones (y operadores): np.bitwise_and( &operador)
>>> 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)
y bitwise_or( |operador):
>>> 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)
Puede encontrar una lista completa de funciones lógicas y binarias en la documentación de NumPy: