ValueError:包含多个元素的数组的真值是不明确的。使用.any()或a.all()我刚刚在我的代码中发现了一个逻辑错误,它导致了各种各样的问题。我无意中做了一个按位和而不是逻辑与.我将代码更改为: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]令我惊讶的是,我得到了一个相当神秘的错误信息:ValueError:包含多个元素的数组的真值是不明确的。使用.any()或a.all()为什么在使用按位操作时没有发出类似的错误-以及如何修复这个错误?
3 回答
DIEA
TA贡献1820条经验 获得超2个赞
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 arrValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()>>> if arr: passValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()>>> while arr: passValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()>>> arr or arrValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
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
.
<
, <=
, ==
, !=
, >=
>
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)
添加回答
举报
0/150
提交
取消