在两个数组中打印不匹配的项目

时间:2017-08-16 12:07:47

标签: python-3.x numpy

我想比较两个数组(4个浮点)和打印不匹配的项目。 我用了这段代码:

>>> from numpy.testing import assert_allclose as np_assert_allclose
>>> x=np.array([1,2,3])
>>> y=np.array([1,0,3])
>>> np_assert_allclose(x,y, rtol=1e-4)

AssertionError: 
Not equal to tolerance rtol=0.0001, atol=0

(mismatch 33.33333333333333%)
 x: array([1, 2, 3])
 y: array([1, 0, 3])

此代码的问题是大数组:

(mismatch 0.0015104228617559556%)
 x: array([ 0.440088,  0.35994 ,  0.308225, ...,  0.199546,  0.226758,  0.2312  ])
 y: array([ 0.44009,  0.35994,  0.30822, ...,  0.19955,  0.22676,  0.2312 ])

我找不到哪些值不匹配。怎么能看到他们?

1 个答案:

答案 0 :(得分:4)

只需使用

~np.isclose(x, y, rtol=1e-4)  # array([False,  True, False], dtype=bool)

e.g。

d = ~np.isclose(x, y, rtol=1e-4)
print(x[d])  # [2]
print(y[d])  # [0]

或者,获取指数

np.where(d)  # (array([1]),)
相关问题