有没有办法找到一个整数偏移量,当添加到一个 numpy 数组中的每个值时,它会最大化它与另一个数组的匹配量?

问题描述

例如说我有 2 个列表:

a = np.array([1,3,5,6,8,9])
b = np.array([103,104,106,107,108,109])

我想要添加的值是 ~100 以添加到列表 a 作为偏移量,以匹配给定偏移量的尽可能多的列表 b 值。

我目前的解决方案基本上是

best_matches = []
for v1 in a:
    for v2 in b:
        offset = abs(v1 - v2)
        matches = np.intersect1d(a + offset,b)

        best_matches.append((offset,len(matches)))

best_offset = max(best_matches,key = lambda i : i[1]) # find offset that had the most amount of intersections when added to the first array

我需要解决方案来处理相当大的值列表,因此解决方案只需要更有效或在方法上有所不同。任何帮助表示赞赏!

解决方法

相当于没有循环的答案:

o = np.bincount(np.ravel(b[:,None] - a[None,:])).argmax()
l = len(np.intersect1d(b,(a + o)))
>>> (o,l)
(98,4)

根据评论更新 @AlexanderS.Brunmayr@Blckknght