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()

查看:151
本文介绍了ValueError:具有多个元素的数组的真值不明确.使用a.any()或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)数组.因此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,或者如果 all 元素均为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 每当有人尝试在布尔上下文中求值数组时.将and应用于 两个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]

看起来正确.但是,如果您确实想要and,请使用(a-b).any()(a-b).all()代替a and b.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆