通常情况下,这个错误信息是由于试图使用Python布尔运算符(not
,and
,or
)或涉及NumPy数组的比较表达式而导致的,例如:
>>> x = np.arange(-5, 5)
>>> (x > -2) and (x < 2)
Traceback (most recent call last):
File "<ipython-input-6-475a0a26e11c>", line 1, in <module>
(x > -2) and (x < 2)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是因为这种比较,与 Python 内置类型之间的比较不同,会创建布尔数组而不是单个布尔值:
>>> x > -2
array([False, False, False, False, True, True, True, True, True, True], dtype=bool)
>>> x < 2
array([ True, True, True, True, True, True, True, False, False, False], dtype=bool)
要解决这个问题,请将 and
运算符替换为调用 np.logical_and
,它会在两个 np.bool
数组之间广播 AND 运算。
>>> np.logical_and(x > -2, x < 2)
array([False, False, False, False, True, True, True, False, False, False], dtype=bool)
>>> x[np.logical_and(x > -2, x < 2)]
array([-1, 0, 1])
然而,这样的布尔数组不能用于索引普通的Python列表,因此列表推导的结果必须先转换为数组:
rbs = np.array([ish[4] for ish in realbooks])
and
导致的,这恰好是标准设置),这里给出的标题有误导性 - 问题并没有发生在“尝试索引数组”时,而是在试图使用and
结合两个掩码时发生。 - Karl Knechtel