gpt4 book ai didi

python - 两个点层之间的距离矩阵

转载 作者:行者123 更新时间:2023-12-04 11:02:30 26 4
gpt4 key购买 nike

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

例如:

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

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

enter image description here

现在我有这个功能:
    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)

有没有更快的方法来做到这一点?我想有,但我不知道如何进行。我也许可以将数据帧分成更小的部分,然后将 block 发送到不同的核心并连接结果 - 这是最后的手段。如果我们能以某种方式仅使用一些索引魔法,我可以将它发送到 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)

关于python - 两个点层之间的距离矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713739/

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