有没有一个类似于np.isin的numpy函数,它允许一个容差,而不是要求值是相同的?

smdnsysy  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(65)

我有两个不同大小的数组,想确定一个数组的元素在另一个数组中的位置。我希望能够允许元素之间的公差。目标应该是这样的:

array1 = [1, 2, 3, 4, 5, 6]
array2 = [2, 8, 1.00001, 1.1]

places = [mystery function](array1, array2, tolerance = 0.001)

返回array1中的索引places = [0,1]
我能得到的最接近的是np.isin,它允许不同大小和顺序的数组,但不允许公差。(也尝试过np.allclose,但形状和顺序不匹配是一个问题)。当然,这可以用循环来完成,但我的实际数组有数千个元素长,所以循环是不实用的。
(it也不必是numpy函数--实际上只是比循环更有效的函数)
提前感谢您的帮助!

k4emjkb1

k4emjkb11#

使用自定义函数查找2个阵列和符合给定公差的位置之间的绝对差异:

array1 = np.array([1, 2, 3, 4, 5, 6])
array2 = np.array([2, 8, 1.00001, 1.1])
tolerance = 0.001

def argwhere_close(a, b, tol):
    return np.where(np.any(np.abs(a - b[:, None]) <= tolerance, axis=0))[0]

print(argwhere_close(array1, array2, tolerance))
[0 1]
wd2eg0qa

wd2eg0qa2#

虽然我不知道numpy中有什么函数,但我确实写了一个。
希望这对你有帮助:

import numpy as np

def find_indices_within_tolerance(array1, array2, tolerance):
    results = []
    for i, a1_elem in enumerate(array1):
        for a2_elem in array2:
            if abs(a1_elem - a2_elem) <= tolerance:
                results.append(i)
    results = list(set(results))
    results.sort()
    return results

array1 = np.array([1, 2, 3, 4, 5, 6])
array2 = np.array([2, 8, 1.00001, 1.1])

places = find_indices_within_tolerance(array1, array2, tolerance=0.001)

print(places)

-> yields: [0, 1]

相关问题