什么是“in”numpy数组是什么意思

时间:2013-10-30 15:46:58

标签: python numpy

我有一些代码,而我喜欢它要做的是:

>> x=np.zeros((40,2))
>> x[31]=(12,15)
>> y=x.copy()
>> y[31]=(12,4)

#the following behavior is correct, but the syntax is unwieldy with the
#conversions to float and list, quite annoying

>> e=[12.,15.] 
>> e in x.tolist()
True
>> e in y.tolist()
False

然而,在调试过程中,我发现了以下奇怪的行为:

>> e in x
True
>> e in y
True

即使

>> f=(8,93)
>> f in x
False

我的问题有两个:

a)numpy在这里做什么来产生这个结果?

b)除了使用tolist和浮点转换(除了使用python级for循环)之外,还有其他方法可以完成此检查吗?这种设计并不明显,也不易维护。

1 个答案:

答案 0 :(得分:2)

认为 in将为您提供相当于np.any(y == e)的结果,其中维度会自动广播。如果您查看y == e(粘贴在此答案的底部),则会有一个True元素。比我更了解情况的人会知道究竟发生了什么。

可能有一种更简洁的方法,但我建议不要转换为列表:

>>> np.any(np.all(x == e, axis=-1))
True
>>> np.any(np.all(y == e, axis=-1))
False

y == e的输出看起来像

>>> y == e
array([[False, False],
       ...
       [False, False],
       [ True, False],
       [False, False],
       ...
       [False, False]], dtype=bool)
相关问题