Home > Back-end >  How to find close/common values among two 2D arrays?
How to find close/common values among two 2D arrays?

Time:12-06

Suppose I have 2 numpy arrays containing unique BGR values, like:

arr1 = np.array([[159, 102, 66], [151, 92, 58], [155, 96, 62]])

arr2 = np.array([[161, 104, 68], [159, 102, 66], [159, 101, 67]])

I want to find common values among those arrays independent of order, for this example I am interested in finding the common values and number of common values, like: [[159, 102, 66]] and the number of elements as 1.

Lastly, I want to know if there is a way to do this operation with close values, like I want to find [159, 101, 67] along with [[159, 102, 66]] from arr2, since it's very close to [159, 102, 66] from arr1. It doesn't matter which value I get (whether from arr1 or arr2) when there are close values, because I am mainly intrested in number of common/close values for this operation.

CodePudding user response:

With you can use broadcasting:

thresh = 1

out = (abs(arr1[:,None]-arr2)<=thresh).all(axis=-1)

Output:

# arr2: row0    row1   row2      # arr1:
array([[False,  True,  True],    # row0
       [False, False, False],    # row1
       [False, False, False]])   # row2

You can then get the rows for each array using:

arr1[out.any(axis=1)]
# array([[159, 102,  66]])


arr2[out.any(axis=0)]
# array([[159, 102,  66],
#        [159, 101,  67]])

CodePudding user response:

You might find common sub-arrays using built-in set arithemtic however you need to convert sub-arrays into hashable type(s) first, I would use tuple following way

import numpy as np
arr1 = np.array([[159, 102, 66], [151, 92, 58], [155, 96, 62]])
arr2 = np.array([[161, 104, 68], [159, 102, 66], [159, 101, 67]])
set1 = set(map(tuple,arr1))
set2 = set(map(tuple,arr2))
common = set1.intersection(set2)
print(common)

output

{(159, 102, 66)} # set holding single tuple
  • Related