Home > Blockchain >  Return difference of two 2D arrays
Return difference of two 2D arrays

Time:11-25

I have 2 2d arrays and I would like to return all values that are differing in the second array while keeping the existing dimensions. I've done something like diff = arr2[np.nonzero(arr2-arr1)] works to give me the differing elements but how do I keep the dimensions and relative position of the elements?

Example Input:

arr1 = [[0 1 2]  arr2 = [[0 1 2]
        [3 4 5]          [3 5 5]
        [6 7 8]]         [6 7 8]]

Expected output:

diff = [[0 0 0]
        [0 5 0]
        [0 0 0]]

CodePudding user response:

How about the following:

import numpy as np

arr1 = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
arr2 = np.array([[0, 1, 2], [3, 5, 5], [6, 7, 8]])
diff = arr2 * ((arr2 - arr1) != 0)

print(diff)
# [[0 0 0]
#  [0 5 0]
#  [0 0 0]]

EDIT: Surprisingly to me, the following first version of my answer (corrected by OP) might be faster:

diff = arr2 * np.abs(np.sign(arr2 - arr1))

CodePudding user response:

If they are numpy arrays, you could do

ans = ar1 * 0
ans[ar1 != ar2] = ar2[ar1 != ar2]
ans
# array([[0, 0, 0],
#        [0, 5, 0],
#        [0, 0, 0]])

Without numpy, you can use map

list(map(lambda a, b: list(map(lambda x, y: y if x != y else 0, a, b)), arr1, arr2))
# [[0, 0, 0], [0, 5, 0], [0, 0, 0]]

Data

import numpy as np

arr1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
arr2 = [[0, 1, 2], [3, 5, 5], [6, 7, 8]]

ar1 = np.array(arr1)
ar2 = np.array(arr2)

CodePudding user response:

I am surprised no one proposed the numpy.where method:

diff = np.where(arr1!=arr2, arr2, 0)

Literally, where arr1 and arr2 are different take the values of arr2, else take 0.

Output:

array([[0, 0, 0],
       [0, 5, 0],
       [0, 0, 0]])

CodePudding user response:

np.copyto

You can check for inequality between the two arrays then use np.copyto with np.zeros/ np.zeros_like.

out = np.zeros(arr2.shape) # or np.zeros_like(arr2)
np.copyto(out, arr2, where=arr1!=arr2)
print(out)

# [[0 0 0]
#  [0 5 0]
#  [0 0 0]]

np.where

You can use np.where and specify x, y args.

out = np.where(arr1!=arr2, arr2, 0)

# [[0 0 0]
#  [0 5 0]
#  [0 0 0]]
  • Related