Tengo dos matrices numpy y quiero probar la igualdad.
Lo siguiente funciona correctamente:
# 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)Sin embargo, si una de las matrices internas está irregular, la comparación falla:
# 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)ACTUALIZAR:
Para hacer la historia aún más oscura, lo siguiente funciona:
x = np.array([np.array(['a', 'b']), np.array(['c'])], dtype='object') y = x np.testing.assert_array_equal(x,y)¿Es este el comportamiento correcto?
En el primer caso, las matrices son (2,2) (a pesar del tipo de objeto):
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]])La afirmación solo tiene que verificar que todos los elementos de esta comparación sean Verdaderos
El segundo caso:
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 El resultado es un escalar, no una matriz (2,). x==x produce True , con la misma advertencia.
Los elementos de la matriz se pueden comparar por pares:
In [30]: [i==j for i,j in zip(x,y)] Out[30]: [array([ True, True]), array([ True])]