在对 numpy 数组使用按位运算符和比较运算符时,内部会发生什么并引发 ValueError?
What happens internally and raises ValueError while using bitwise and comparison operators with numpy arrays?
import numpy as np
arr = np.array([3, 4, 6, 15, 25, 38])
print(arr > 5 & arr <= 20)
"""Output
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(arr > 5 & arr <= 20)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""
我知道发生此错误是因为我错过了条件周围的括号。但我想知道表达式的计算顺序以及导致此错误的原因。
&
有一个higher precedence than <=
, so this is being run as arr > (5 & arr) <= 20
and since comparison operators are chained,这相当于:
(arr > (5 & arr)) and (arr <= (5 & arr))
这会导致众所周知的错误,因为您不能在布尔上下文中使用数组,正如错误消息所解释的那样...(旁注,5 & arr
仅计算一次...)
所以考虑一下,即使这样也会失败:
>>> arr = np.array([1,2,3,4,5])
>>> 0 < arr < 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
arr = np.array([3, 4, 6, 15, 25, 38])
print(arr > 5 & arr <= 20)
"""Output
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(arr > 5 & arr <= 20)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""
我知道发生此错误是因为我错过了条件周围的括号。但我想知道表达式的计算顺序以及导致此错误的原因。
&
有一个higher precedence than <=
, so this is being run as arr > (5 & arr) <= 20
and since comparison operators are chained,这相当于:
(arr > (5 & arr)) and (arr <= (5 & arr))
这会导致众所周知的错误,因为您不能在布尔上下文中使用数组,正如错误消息所解释的那样...(旁注,5 & arr
仅计算一次...)
所以考虑一下,即使这样也会失败:
>>> arr = np.array([1,2,3,4,5])
>>> 0 < arr < 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()