Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 923
Rtrader Avatar asked Sep 28 '12 21:09

Rtrader


People also ask

How do you fix the truth value of an array with more than one element is ambiguous use a ANY () or a all ()?

Use a. any() or a. all() if you try to get the truth value of a numpy array with more than one element. To solve this error, you can use the any() function if you want at least one element in the array to return True or the all() function if you want all the elements in the array to return True.

What is the truth value of an array?

For 1 or 0 elements ValueError: The truth value of an array with more than one element is ambiguous. If the number of elements is one, the value of the element is evaluated as a bool value. For example, if the element is an integer int , it is False if it is 0 and True otherwise.

How do you use a ANY () or a all () in Python?

The Python any() and all() functions evaluate the items in a list to see which are true. The any() method returns true if any of the list items are true, and the all() function returns true if all the list items are true.


1 Answers

As I told you in a comment to a previous answer, you need to use either:

c[a & b]

or

c[np.logical_and(a, b)] 

The reason is that 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.

So, you either have to use the logical function to compare two boolean arrays on an element-by-element basis (np.logical_and) or the binary operator &.

Moreover, for indexing purposes, you really need a boolean array with the same size as the array you're indexing. And it has to be an array, you cannot use a list of True/False instead: The reason is that using a boolean array tells NumPy which element to return. If you use a list of True/False, NumPy will interpret that as a list of 1/0 as integers, that is, indices, meaning that you' either get the second or first element of your array. Not what you want.

Now, as you can guess, if you want to use two boolean arrays a or b for indexing, choosing the items for which either a or b is True, you'd use

c[np.logical_or(a,b)]

or

c[a | b]
like image 164
Pierre GM Avatar answered Sep 19 '22 17:09

Pierre GM