0

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?

3 Answers 3

2
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])]
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think this quite works. e.g. 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])]
I tested it on your original lists which matched in length. You may need to add a len(myarray1(==len(myarray2) test first. zip stops with the shortest list.
0

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

Alternatively, all(array1 == array2)

1 Comment

did you test that on the OP's example?
0

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.

2 Comments

Why would the second example evaluate to false if all elements are the same?
Refer to @hpaulj's solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.