简体   繁体   English

如何在两个 2D arrays 之间找到接近/共同的价值?

[英]How to find close/common values among two 2D arrays?

Suppose I have 2 numpy arrays containing unique BGR values, like:假设我有 2 numpy arrays 包含唯一的 BGR 值,例如:

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 .我想在 arrays 中找到独立于顺序的公共值,对于这个例子,我有兴趣找到公共值和公共值的数量,例如: [[159, 102, 66]]和元素的数量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 .最后,我想知道是否有办法使用接近值执行此操作,就像我想从arr2中找到[159, 101, 67][[159, 102, 66]]一样,因为它非常接近[159, 102, 66]来自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.当有接近值时,我得到哪个值(无论是从arr1还是arr2 )并不重要,因为我主要对这个操作的公共/接近值的数量感兴趣。

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您可能会发现使用内置集合算术的常见子数组但是您需要先将子数组转换为可散列类型,我会按照以下方式使用tuple

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 output

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

With you can use broadcasting:使用您可以使用广播:

thresh = 1

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

Output: 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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM