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?
You usually get this error message when trying to use Python boolean operators (
not
,and
,or
) on comparison expressions involving Numpy arrays, e.g.That's because such comparisons, as opposed to other comparisons in Python, create arrays of booleans rather than single booleans (but maybe you already knew that):
Part of the solution to your problem probably to replace
and
bynp.logical_and
, which broadcasts the AND operation over two arrays ofnp.bool
.However, such arrays of booleans cannot be used to index into ordinary Python lists, so you need to convert that to an array:
As I told you in a comment to a previous answer, you need to use either:
or
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 areTrue
, is itTrue
orFalse
? 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 ofTrue/False
, NumPy will interpret that as a list of1/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
orb
for indexing, choosing the items for which eithera
orb
is True, you'd useor