我的问题是“为什么?”
aa[0]
array([[405, 162, 414, 0,
array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],
dtype=object),
0, 0, 0]], dtype=object)
aaa
array([[405, 162, 414, 0,
array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],
dtype=object),
0, 0, 0]], dtype=object)
np.array_equal(aaa,aa[0])
False
这些数组完全相同。
我的最小示例没有重现这一点:
be=np.array([1],dtype=object)
be
array([1], dtype=object)
ce=np.array([1],dtype=object)
ce
array([1], dtype=object)
np.array_equal(be,ce)
True
这个也没有:
ce=np.array([np.array([1]),'5'],dtype=object)
be=np.array([np.array([1]),'5'],dtype=object)
np.array_equal(be,ce)
True
但是,要重现我的问题,请尝试以下操作:
be=np.array([[405, 162, 414, 0, np.array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],dtype=object),0, 0, 0]], dtype=object)
ce=np.array([[405, 162, 414, 0, np.array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],dtype=object),0, 0, 0]], dtype=object)
np.array_equal(be,ce)
False
np.array_equal(be[0],ce[0])
False
而且我不知道为什么它们不相等。并添加奖金问题,我如何比较它们?
我需要一种有效的方法来检查 aaa 是否在堆栈 aa 中。
我没有在 aa 中使用 aaa
因为 DeprecationWarning: elementwise == comparison failed;这将在未来引发错误。
并且因为如果有人想知道它仍然返回 False
。
我还尝试了什么?:
np.equal(be,ce)
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
np.all(be,ce)
*** TypeError: only integer scalar arrays can be converted to a scalar index
all(be,ce)
*** TypeError: all() takes exactly one argument (2 given)
all(be==ce)
*** TypeError: 'bool' object is not iterable
np.where(be==ce)
(array([], dtype=int64),)
而这些,我无法在控制台中运行,全部评估为 False,一些给出弃用警告:
import numpy as np
ce=np.array([[405, 162, 414, 0, np.array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],dtype=object),0, 0, 0]], dtype=object)
be=np.array([[405, 162, 414, 0, np.array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],dtype=object),0, 0, 0]], dtype=object)
print(np.any([bee in ce for bee in be]))
print(np.any([bee==cee for bee in be for cee in ce]))
print(np.all([bee in ce for bee in be]))
print(np.all([bee==cee for bee in be for cee in ce]))
当然还有other questions告诉我这应该有效...
最佳答案
要在数组之间进行逐元素比较,您可以使用 numpy.equal()
使用关键字参数 dtype=numpy.object
如:
In [60]: np.equal(be, ce, dtype=np.object)
Out[60]:
array([[True, True, True, True,
array([ True, True, True, True, True]), True, True, True]],
dtype=object)
P.S. 使用 NumPy 版本 1.15.2
和 Python 3.6.6
进行检查
编辑
来自 1.15 的发行说明,
Comparison ufuncs accept dtype=object, overriding the default bool
This allows object arrays of symbolic types, which override == and
other operators to return expressions, to be compared elementwise with
np.equal(a, b, dtype=object).
关于python - 比较 dtype 对象的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52715049/