How to compare two arrays of arrays 'array-elementwise' in Numpy?


Given two arrays of arrays A and B, I need to test the equality of each subarray from A (ai) to its corresponding subarray in B (bi):

import numpy as np

a1 = np.array([1, 2, 3])
a2 = np.array([3, 4, 5])
a3 = np.array([2, 4, 6])
A = np.array([a1, a2, a3])

b1 = np.array([3, 2, 1])
b2 = np.array([3, 4, 5])
b3 = np.array([6, 4, 2])
B = np.array([b1, b2, b3])

def compare_arrays(A, B):
    #ret = A == B
    #ret = np.array_equal(A, B)
    return ret

print(compare_arrays(A, B))

Unsurprisingly, the output I get with A == B: [[False True False][ True True True][False True False]].

Unsurprisingly, the output I get with np.array_equal(A, B): False.

The output I would like to get: [[False, True, False]].

I would like to know if there exists an off-the-shelf solution that I have not found or if I should implement my own.

Show source
| numpy   | python   2017-01-07 16:01 2 Answers

Answers ( 2 )

  1. 2017-01-07 16:01

    You can use something like this:

    def compare_arrays(A, B):
        return map(lambda item: not False in item, A==B)
  2. 2017-01-07 16:01

    You can get logical and results along axis=1 from A == B.

    def compare_arrays(A, B):
        ret = np.equal(A, B).all(axis=1)
        return ret
◀ Go back