问题很简单,我有两个 DataFrame :
一个有 90 000 套公寓及其纬度/经度
一个有 3 000 个药房及其纬度/经度
我想为我所有的公寓创建一个新变量:“最近药房的距离”
为此,我尝试了两种花费大量时间的方法:
第一种方法:我创建了一个矩阵,其中我的公寓在行中,我的药房在列中,它们之间的距离在交集处,之后我只取矩阵的最小值以获得 90 000 值的列向量
我只是使用 double for with numpy :
m,n=len(result['latitude']),len(pharma['lat'])
M = np.ones((m,n))
for i in range(m):
for j in range(n):
if (result['Code departement'][i]==pharma['departement'][j]):
M[i,j] =(pharma['lat'][j]-result['latitude'][i])**2+(pharma['lng'][j]-result['longitude'] [i])**2
Run Code Online (Sandbox Code Playgroud)
ps:我知道纬度/经度的公式是错误的,但公寓在同一地区,所以这是一个很好的近似值
第二种方法:我使用这个主题的解决方案(他们是同样的问题,但数据较少) https://gis.stackexchange.com/questions/222315/geopandas-find-nearest-point-in-other-dataframe
我使用了geopandas et最近的方法:
from shapely.ops import nearest_points
pts3 = pharma.geometry.unary_union
def near(point, pts=pts3):
nearest = pharma.geometry == nearest_points(point, pts)[1]
return pharma[nearest].geometry.get_values()[0]
appart['Nearest'] = appart.apply(lambda row: near(row.geometry), axis=1)
Run Code Online (Sandbox Code Playgroud)
正如我所说,这两种方法都花费了太多时间,在运行 1 小时后我的电脑/笔记本崩溃并且失败了。
我的最后一个问题: …