0

I'm trying to compare two identical nested numpy arrays:

In [1]: a1 = np.array([np.array([1, 1, 1]), np.array([2, 2, 2]), np.array([3])], dtype=object)         
In [2]: a2 = np.array([np.array([1, 1, 1]), np.array([2, 2, 2]), np.array([3])], dtype=object)         

I saw here that in order to compare two arrays of dtype object I need to use numpy.equal() with the keyword argument dtype=numpy.object.

In [3]: e = np.equal(a1, a2, dtype=object)                                                             
In [4]: e                                                                                              
Out[4]: 
array([array([ True,  True,  True]), array([ True,  True,  True]),
       array([ True])], dtype=object)

However, e.all is raising an exception:

In [5]: e.all()                                                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-afa4ead28930> in <module>
----> 1 e.all()

/usr/local/lib/python3.8/dist-packages/numpy/core/_methods.py in _all(a, axis, dtype, out, keepdims)
     55 
     56 def _all(a, axis=None, dtype=None, out=None, keepdims=False):
---> 57     return umr_all(a, axis, dtype, out, keepdims)
     58 
     59 def _count_reduce_items(arr, axis):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How can I compare these arrays?

MKL
  • 1

2 Answers2

-1

You can stack them and then check for all:

np.hstack(e).all()
#True
Ehsan
  • 12,072
  • 2
  • 20
  • 33
-1

Alternatlivley, and mainly to demonstrate the issue, that what is the error means:

Instead of doing:

e.all()

You can reach each element to check all

all(arr.all() for arr in e.tolist())

Because you got an array that contains more arrays, and not a ndarray (matrix) the built in all treat each array as boolean, and this is what causes your error..

Again i didnt check timing and could be that the other answer is faster, but i came mainly to explain...

adir abargil
  • 5,495
  • 3
  • 19
  • 29