gpt4 book ai didi

python - 计算包含 NaN 的数组之间的距离

转载 作者:行者123 更新时间:2023-12-03 16:35:19 25 4
gpt4 key购买 nike

考虑 array1array2 , 和:

array1 = [a1 a2 NaN ... an]
array2 = [[NaN b2 b3 ... bn],
[b21 NaN b23 ... b2n],
...]

两个数组都是 numpy 数组。有一种简单的方法可以计算 array1 之间的欧几里得距离和每一行 array2 :
EuclideanDistance = np.sqrt(((array1 - array2)**2).sum(axis=1))

搞乱这个计算的是 NaN 值。当然,我可以很容易地用一些数字替换 NaN。但相反,我想做以下事情:

当我比较时 array1row_xarray2 ,我计算其中一个数组有 NaN 而另一个没有的列。让我们假设 count是 3。然后我将从两个数组中删除这些列并计算两者之间的欧几里德距离。最后我加了一个 minus_value * count到计算的距离。

现在,我想不出一种快速有效的方法来做到这一点。有人可以帮助我吗?

以下是我的一些想法:
minus = 1000
dist = np.zeros(shape=(array1.shape[0])) # this array will store the distance of array1 to each row of array2
array1 = np.repeat(array1, array2.shape[0], axis=0) # now array1 has the same dimensions as array2
for i in range(0, array1.shape[0]):
boolarray = np.logical_or(np.isnan(array1[i]), np.isnan(array2[i]))
count = boolarray.sum()
deleteIdxs = boolarray.nonzero() # this should give the indices where boolarray is True
dist[i] = np.sqrt(((np.delete(array1[i], deleteIdxs, axis=0) - np.delete(array2[i], deleteIdxs, axis=0))**2).sum(axis=0))
dist[i] = dist[i] + count*minus

然而,这些线条对我来说并不难看。此外,我不断收到索引错误:显然 deleteIdxs 包含超出 array1 范围的索引。不知道这怎么可能。

最佳答案

您可以使用以下方法找到值为 nan 的所有索引:

indices_1 = np.isnan(array1)
indices_2 = np.isnan(array2)

您可以结合使用:
indices_total = indices_1 + indices_2

您可以使用以下方法保留所有 not nan 值:
array_1_not_nan = array1[~indices_total]
array_2_not_nan = array2[~indices_total]

关于python - 计算包含 NaN 的数组之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61677154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com