Equality of structures containing numpy arrays

Viewed 60

It's well-known that == on numpy arrays returns an array rather than a bool, but this is very inconvenient at times.

>>> [np.zeros(4)] == [np.zeros(4)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

In my case, I have a huge structure of nested dicts, lists, etc, which occasionally contains numpy arrays. The fact that they can potentially contain numpy arrays means that == can't be used for comparisons since it will occasionally throw exceptions, so instead I need to traverse it manually. This is slow, verbose, and just overall annoying. Is there any better workaround?

1 Answers

np.array_equal seems to do the trick:
From the doc:

>>> np.array_equal([1, 2], [1, 2])
True
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
>>> np.array_equal([1, 2], [1, 2, 3])
False
>>> np.array_equal([1, 2], [1, 4])
False
>>> a = np.array([1, np.nan])
>>> np.array_equal(a, a)
False
>>> np.array_equal(a, a, equal_nan=True)
True

It seems to work well also with object with any level of nesting:

x = {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': True}}}}}}}}
y = {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': True}}}}}}}}
>>> np.array_equal(x, y)
True

z = {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': False}}}}}}}}
>>> np.array_equal(x, z)
False

u = {'a': 0, 'b': 1}
v = {'b': 1, 'a': 0}
>>> np.array_equal(u, v)
True
Related