Search code examples
pythonnumpylist-comprehension

The truth value of an array with more than one element is ambigous when trying to index an array


I am trying to put all elements of rbs into a new array if the elements in var(another numpy array) is >=0 and <=.1 . However when I try the following code I get this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

rbs = [ish[4] for ish in realbooks]
for book in realbooks:
    var -= float(str(book[0]).replace(":", ""))
    bidsred = rbs[(var <= .1) and (var >=0)]

any ideas on what I'm doing wrong?


Solution

  • The and keyword is used by Python to test between two booleans. How can an array be a boolean? If 75% of its items are True, is it True or False? Therefore, numpy refuses to compare the two.

    Therefore, use either c[a & b] or c[np.logical_and(a, b)]. Either approach to combining the a and b arrays - a & b or np.logical_and(a, b) - will produce a boolean array with the same size as the input arrays a and b, which is necessary if the next step is to index into a same-sized array c.

    A list of boolean values cannot be used for indexing instead. NumPy will interpret that as a list of index values (treating True as 1 and False as 0), so the output would contain multiple copies of the first two elements of the array, rather than a masked version.

    Similarly, to choose elements from c where either of the corresponding elements from a or b is true, use c[a | b] or c[np.logical_or(a,b)].