Ang*_*elo 5 python arrays numpy
我有两个 numpy 数组,我想测试是否相等。
以下正确运行:
# this works
x = np.array([np.array(['a', 'b']), np.array(['c', 'd'])], dtype='object')
y = np.array([np.array(['a', 'b']), np.array(['c', 'd'])], dtype='object')
assert np.testing.assert_array_equal(x,y)
Run Code Online (Sandbox Code Playgroud)
然而,如果内部数组之一不规则,比较就会失败:
# this works
x = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object')
y = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object')
np.testing.assert_array_equal(x,y)
Traceback (most recent call last):
File "/home/.../test.py", line 12, in <module>
np.testing.assert_array_equal(x,y)
File "/home/.../lib/python3.9/site-packages/numpy/testing/_private/utils.py", line 932, in assert_array_equal
assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
File "/home/.../lib/python3.9/site-packages/numpy/testing/_private/utils.py", line 842, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal
Mismatched elements: 1 / 1 (100%)
x: array([array(['a', 'b'], dtype='<U1'), array(['c'], dtype='<U1')],
dtype=object)
y: array([array(['a', 'b'], dtype='<U1'), array(['c'], dtype='<U1')],
dtype=object)
Run Code Online (Sandbox Code Playgroud)
更新:
为了使故事更加晦涩难懂,以下作品:
x = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object')
y = x
np.testing.assert_array_equal(x,y)
Run Code Online (Sandbox Code Playgroud)
这是正确的行为吗?
在第一种情况下,数组为 (2,2)(尽管对象数据类型不同):
In [20]: x = np.array([np.array(['a', 'b']), np.array(['c', 'd'])], dtype='object')
...: y = np.array([np.array(['a', 'b']), np.array(['c', 'd'])], dtype='object')
In [21]: x
Out[21]:
array([['a', 'b'],
['c', 'd']], dtype=object)
In [22]: x.shape
Out[22]: (2, 2)
In [23]: x==y
Out[23]:
array([[ True, True],
[ True, True]])
Run Code Online (Sandbox Code Playgroud)
断言只需验证此比较的所有元素是否均为 True
第二种情况:
In [24]: x = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object')
...: y = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object')
In [25]: x
Out[25]:
array([array(['a', 'b'], dtype='<U1'), array(['c'], dtype='<U1')],
dtype=object)
In [26]: x.shape
Out[26]: (2,)
In [27]: x==y
<ipython-input-27-051436df861e>:1: DeprecationWarning: elementwise comparison failed;
this will raise an error in the future.
x==y
Out[27]: False
Run Code Online (Sandbox Code Playgroud)
结果是标量,而不是 (2,) 数组。 x==x产生True,并带有相同的警告。
数组元素可以成对比较:
In [30]: [i==j for i,j in zip(x,y)]
Out[30]: [array([ True, True]), array([ True])]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |