ValueError:包含多个元素的数组的真值不明确.使用 a.any() 或 a.all() [英] ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
问题描述
我刚刚在我的代码中发现了一个导致各种问题的逻辑错误.我无意中做了一个按位与而不是逻辑与.
I just discovered a logical bug in my code which was causing all sorts of problems. I was inadvertently doing a bitwise AND instead of a logical AND.
我更改了代码:
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]
致:
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) and (r["dt"] <= enddate))
selected = r[mask]
令我惊讶的是,我收到了一个相当神秘的错误消息:
To my surprise, I got the rather cryptic error message:
ValueError: 多于一个元素的数组的真值是模糊的.使用 a.any() 或 a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
为什么在我使用按位运算时没有发出类似的错误 - 我该如何解决这个问题?
Why was a similar error not emitted when I use a bitwise operation - and how do I fix this?
推荐答案
r
是一个 numpy (rec)array.所以 r["dt"] >= startdate
也是一个(布尔值)大批.对于 numpy 数组,&
操作返回两个元素的和布尔数组.
r
is a numpy (rec)array. So r["dt"] >= startdate
is also a (boolean)
array. For numpy arrays the &
operation returns the elementwise-and of the two
boolean arrays.
NumPy 开发人员认为没有一种普遍理解的评估方法布尔上下文中的数组:如果 any 元素是,它可能意味着 True
True
,或者如果 所有 元素都是 True
或 True
,则它可能意味着 True
如果数组具有非零长度,仅举出三种可能性.
The NumPy developers felt there was no one commonly understood way to evaluate
an array in boolean context: it could mean True
if any element is
True
, or it could mean True
if all elements are True
, or True
if the array has non-zero length, just to name three possibilities.
由于不同的用户可能有不同的需求和不同的假设,NumPy 开发人员拒绝猜测,而是决定引发 ValueError每当有人尝试在布尔上下文中评估数组时.将 和
应用到两个 numpy 数组导致在布尔上下文中对这两个数组求值(通过在 Python3 中调用 __bool__
或在 Python2 中调用 __nonzero__
).
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError
whenever one tries to evaluate an array in boolean context. Applying and
to
two numpy arrays causes the two arrays to be evaluated in boolean context (by
calling __bool__
in Python3 or __nonzero__
in Python2).
您的原始代码
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]
看起来正确.但是,如果您确实需要 和
,则使用 (ab).any()
或 (ab) 代替
.a 和 b
.all()
looks correct. However, if you do want and
, then instead of a and b
use (a-b).any()
or (a-b).all()
.
这篇关于ValueError:包含多个元素的数组的真值不明确.使用 a.any() 或 a.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!