我有一个 300 万个点的 numpy 数组,格式为 [pt_id, x, y, z]
.目标是返回所有具有欧几里得距离的点对两个数字min_d
和 max_d
.
欧几里得距离在 x
之间和 y
而不是 z
.但是,我想用 pt_id_from
保存数组, pt_id_to
, distance
属性。
我正在使用 scipy 的 dist 来计算距离:
import scipy.spatial.distance
coords_arr = np.array([['pt1', 2452130.000, 7278106.000, 25.000],
['pt2', 2479539.000, 7287455.000, 4.900],
['pt3', 2479626.000, 7287458.000, 10.000],
['pt4', 2484097.000, 7292784.000, 8.800],
['pt5', 2484106.000, 7293079.000, 7.300],
['pt6', 2484095.000, 7292891.000, 11.100]])
dists = scipy.spatial.distance.pdist(coords_arr[:,1:3], 'euclidean')
np.savetxt('test.out', scipy.spatial.distance.squareform(dists), delimiter=',')
我应该怎么做才能返回一个表单数组:
[pt_id_from, pt_id_to, distance]
?
最佳答案
您只需通过循环所有可能的组合从数据中创建一个新数组。 itertools
模块非常适合这一点。
n = coords_arr.shape[0] # number of points
D = scipy.spatial.distance.squareform(dists) # distance matrix
data = []
for i, j in itertools.combinations(range(n), 2):
pt_a = coords_arr[i, 0]
pt_b = coords_arr[j, 0]
d_ab = D[i,j]
data.append([pt_a, pt_b, d_ab])
result_arr = np.array(data)
如果内存有问题,您可能需要更改距离查找,而不是使用巨大的矩阵
D
。直接在 dists
中查找值使用 i
和 j
指数。
关于python-2.7 - 在大型 numpy 三维数组上计算二维成对距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410303/