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



例如,假设我有两个列表:

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和@Blckknht

最新更新