This error message normally results from trying to use Python boolean operators (not
, and
, or
) or comparison expressions involving Numpy arrays, e.g.:
>>> 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()
That's because such comparisons, unlike comparisons between built-in Python types, create arrays of booleans rather than single booleans:
>>> 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)
To fix this, replace the and
operator with a call to np.logical_and
, which broadcasts the AND operation over two arrays of np.bool
.
>>> 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])
However, such arrays of booleans cannot be used to index into ordinary Python lists, so the result of the list comprehension must be converted to an array first:
rbs = np.array([ish[4] for ish in realbooks])