尝试对数组进行索引时,包含多个元素的数组的真值不明确 [英] The truth value of an array with more than one element is ambigous when trying to index an array
问题描述
如果var(另一个numpy数组)中的元素> = 0且< =.1,我正在尝试将rbs的所有元素放入一个新数组中.但是,当我尝试以下代码时,出现此错误:
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?
推荐答案
正如我在对先前答案的评论中告诉您的那样,您需要使用以下任一方法:
As I told you in a comment to a previous answer, you need to use either:
c[a & b]
或
c[np.logical_and(a, b)]
原因是Python使用and
关键字在两个布尔之间进行测试.数组如何成为布尔值?如果其项目的75%是True
,是True
还是False
?因此,numpy拒绝比较两者.
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.
因此,您要么必须使用逻辑函数来逐个元素地比较两个布尔数组(np.logical_and
),要么要使用二进制运算符&
.
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 &
.
此外,出于索引目的,您确实需要一个布尔数组,其大小与要索引的数组相同.而且它必须是一个数组,您不能使用True/False
的列表:
原因是使用布尔数组告诉NumPy要返回哪个元素.如果使用True/False
的列表,则NumPy会将其解释为作为整数(即索引)的1/0
列表,这意味着您将获得数组的第二个或第一个元素.不是你想要的.
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.
现在,您可以猜测,如果要使用两个布尔数组a
或b
进行索引,请选择a
或b
为True的项目,您将使用>
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)]
或
c[a | b]
这篇关于尝试对数组进行索引时,包含多个元素的数组的真值不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!