【发布时间】:2018-07-15 04:16:58
【问题描述】:
我目前正在尝试在 Python 中进行一些地理编码。该过程如下:我有两个具有纬度和经度值的数据框(df1 和 df2,房屋和学校),并且希望为 df1 中的每个观察结果在 df2 中找到最近的邻居。我使用以下代码:
from tqdm import tqdm
import numpy as np
import pandas as pd
import math
def distance(lat1, long1, lat2, long2):
R = 6371 # Earth Radius in Km
dLat = math.radians(lat2 - lat1) # Convert Degrees 2 Radians
dLong = math.radians(long2 - long1)
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLong/2) * math.sin(dLong/2) * math.cos(lat1) * math.cos(lat2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = R * c
return d
dists = []
schools =[]
for index, row1 in tqdm(df1.iterrows()):
for index, row2 in df2.iterrows():
dists.append(distance(row1.lat, row1.lng, row2.Latitude, row2.Longitude))
schools.append(min(dists))
del dists [:]
df1["school"] = pd.Series(schools)
代码有效,但需要很长时间。使用 tqdm,我得到 df1 每秒 2 次迭代的平均速度。作为比较,我在 STATA 中使用 geonear 完成了整个任务,df1 (950) 中的所有观察都需要 1 秒。我在 geonear 的帮助文件中读到他们使用聚类,不计算所有距离,而只计算最近的距离。但是,在我添加一个集群功能(这也可能需要 CPU 能力)之前,我想知道是否有人看到了一些方法来加快进程(我是 python 新手,可能有一些效率低下的代码会减慢进程) .或者是否有一个包可以更快地完成这个过程?
如果它需要比 STATA 更长的时间,我会没事的,但不会接近 7 分钟......
提前谢谢你
【问题讨论】:
标签: python algorithm performance geospatial distance