Home > Blockchain >  How do I determine if two lists of numpy arrays are equal
How do I determine if two lists of numpy arrays are equal

Time:04-14

Suppose I have the following arrays:

myarray1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
myarray2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]

I get an error if I do the following:

myarray1==myarray2

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

My ultimate goal is to see if they are both exactly the same. How can I do that?

CodePudding user response:

In [21]: alist1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
    ...: alist2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
In [22]: alist1==alist2
Traceback (most recent call last):
  Input In [22] in <cell line: 1>
    alist1==alist2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Do a test like this:

In [26]: [np.array_equal(a,b) for a,b in zip(alist1, alist2)]
Out[26]: [True, True, True]
In [27]: all(_)
Out[27]: True

list equal checks for identical id, and failing that for ==. But == for arrays is elementwise, so doesn't produce a single value for each pair. We have to work around that, getting a single True/False for each pair, and then combining those.

In [28]: [a==b for a,b in zip(alist1, alist2)]
Out[28]: 
[array([ True,  True,  True,  True]),
 array([ True,  True,  True]),
 array([ True,  True,  True])]

CodePudding user response:

You can use np.array_equal(array1, array2) for this.

Alternatively, all(array1 == array2)

CodePudding user response:

use .array_equal(). But you need to be careful as you have a list of numpy arrays.

import numpy as np

myarray1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
myarray2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]


np.array_equal(myarray1[0], myarray2[0])

True

but

np.array_equal(myarray1, myarray2)

False

@hpailj has the solution though for you above. So accept that solution.

  • Related