例外の理由は、and暗黙的にを呼び出すためboolです。最初に左のオペランド、True次に(左のオペランドがの場合)次に右のオペランド。したがって、x and yと同等bool(x) and bool(y)です。
ただし、boolon a numpy.ndarray(複数の要素が含まれている場合)は、見た例外をスローします。
>>> 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()
bool()呼び出しは、暗黙的であるandが、また、中if、while、or、次の例のいずれも失敗しますので。
>>> 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()
Pythonにboolは、呼び出しを非表示にする関数やステートメントが他にもあります。たとえば、を2 < x < 10記述するもう1つの方法にすぎません2 < x and x < 10。とandを呼びますbool:bool(2 < x) and bool(x < 10)。
の要素ごとの同等物andはnp.logical_and関数であり、同様にのnp.logical_or同等物として使用できますor。
ブール配列の場合-などを比較<、<=、==、!=、>=と>numpyのアレイ上のブールnumpyの配列を返す-あなたはまた、使用することができます要素ごとのビット単位の機能(および演算子): np.bitwise_and(&演算子)
>>> 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)
およびbitwise_or(|演算子):
>>> 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)
論理関数とバイナリ関数の完全なリストは、NumPyのドキュメントにあります。