两个点层之间的距离矩阵

Distance matrix between two point layers

我有两个包含点坐标的数组 shapely.geometry.Point,大小不同。

例如:

[Point(X Y), Point(X Y)...]
[Point(X Y), Point(X Y)...]

我想用距离函数创建这两个数组的 "cross product"。距离函数来自shapely.geometry,是一个简单的几何向量距离计算。我正在尝试在 M:N 点之间创建距离矩阵:

现在我有这个功能:

    source = gpd.read_file(source)
    near = gpd.read_file(near)

    source_list = source.geometry.values.tolist()
    near_list = near.geometry.values.tolist()

    array = np.empty((len(source.ID_SOURCE), len(near.ID_NEAR)))

    for index_source, item_source in enumerate(source_list):
        for index_near, item_near in enumerate(near_list):
            array[index_source, index_near] = item_source.distance(item_near)

    df_matrix = pd.DataFrame(array, index=source.ID_SOURCE, columns = near.ID_NEAR)

哪个做得很好,但速度很慢。 4000 x 4000 点大约需要 100 秒(我有更大的数据集,所以速度是主要问题)。如果可能的话,我想避免这种双重循环。我尝试在 pandas 数据帧中进行操作(速度非常糟糕):

for index_source, item_source in source.iterrows():
         for index_near, item_near in near.iterrows():
             df_matrix.at[index_source, index_near] = item_source.geometry.distance(item_near.geometry)

快一点(但仍然比 numpy 慢 4 倍):

    for index_source, item_source in enumerate(source_list):
        for index_near, item_near in enumerate(near_list):
             df_matrix.at[index_source, index_near] = item_source.distance(item_near)

有更快的方法吗?我想有,但我不知道如何进行。我也许能够将数据帧分块成更小的块并将块发送到不同的核心并连接结果 - 这是最后的手段。如果我们能以某种方式只使用 numpy 和一些索引魔术,我可以将它发送到 GPU 并立即完成。但是双 for 循环现在是不行的。我也不想使用 Pandas/Numpy 以外的任何其他库。我可以使用 SAGA 处理及其点距离模块 (http://www.saga-gis.org/saga_tool_doc/2.2.2/shapes_points_3.html),这非常快,但我正在寻找 Python 唯一的解决方案。

如果你能得到单独向量中的坐标,我会试试这个:

import numpy as np

x = np.asarray([5.6, 2.1, 6.9, 3.1]) # Replace with data
y = np.asarray([7.2, 8.3, 0.5, 4.5]) # Replace with data

x_i = x[:, np.newaxis]
x_j = x[np.newaxis, :]

y_i = y[:, np.newaxis]
y_j = y[np.newaxis, :]

d = (x_i-x_j)**2+(y_i-y_j)**2

np.sqrt(d, out=d)