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.

I changed the code from:

r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]

TO:

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: 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 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.

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.

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

Your original code

mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]

looks correct. However, if you do want and, then instead of a and b use (a-b).any() or (a-b).all().

Python相关问答推荐

django禁止直接分配到多对多集合的前端.使用user.set()

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

形状弃用警告与组合多边形和多边形如何解决

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

使用python playwright从 Select 子菜单中 Select 值

Python日志(log)库如何有效地获取lineno和funcName?

pytest、xdist和共享生成的文件依赖项

在pandas中,如何在由两列加上一个值列组成的枢轴期间或之后可靠地设置多级列的索引顺序,

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

如何从一个维基页面中抓取和存储多个表格?

高效地计算数字数组中三行上三个点之间的Angular

我可以同时更改多个图像吗?

如何在不遇到IndexError的情况下将基数10的整数转换为基数80?

正则表达式反向查找

Fake pathlib.使用pyfakefs的类变量中的路径'

我应该使用哪一个来判断python中枚举值的唯一性?

Pandas 身上的负数造型

在行数据为向量的DataFrame上计算逐行更改

Python-迭代PANAS中的数据框并替换列表中不包含字符串的值

获取每行NumPy最大出现次数的所有值