的原因的例外是and
隱式調用bool
。首先在左操作數上(如果左操作數是True
),然後在右操作數上。所以x and y
相當於bool(x) and bool(y)
。
然而bool
上一個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
只是另一種寫作方式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的文檔中找到:
什麼爲r的'值[ 「DT」]' – 2012-04-08 13:06:17
熊貓[offer文檔](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing) – Greg 2015-06-09 07:35:23