首页 > 解决方案 > 我可以矢量化两个基于纬度/经度寻找最接近邮政编码的 for 循环吗?

问题描述

问题移至 CodeReview:https ://codereview.stackexchange.com/questions/257465/can-i-optimize-two-for-loops-that-look-for-the-closest-zip-code-based-on-lat -lon 我是 python 新手,我的任务是根据纬度和经度查找美国邮政编码。在弄乱了 arcgis 之后,我意识到这给了我某些位置的空值。我最终通过获取包含所有美国代码的数据集并使用欧几里德距离根据其纬度/经度确定最近的邮政编码来完成我的任务。但是,这平均需要大约 1.3 秒来计算,对于我的近百万条记录,每个条目需要一个邮政编码需要一段时间。我认为矢量化是 python 上用来加速任务的东西。但是,我找不到将它应用到我的代码的方法。这是我的代码,任何反馈将不胜感激:

for j in range(len(myFile)):
    p1=0
    p1=0
    point1 = np.array((myFile["Latitude"][j], myFile["Longitude"][j]))  # This is the reference point
    i = 0
    resultZip = str(usZips["Zip"][0])
    dist = np.linalg.norm(point1 - np.array((float(usZips["Latitude"][0]), float(usZips["Longitude"][0]))))
    for i in range(0, len(usZips)):
        lat = float(usZips["Latitude"][i])
        lon = float(usZips["Longitude"][i])
        point2 = np.array((lat, lon))  # This will serve as the comparison from the dataset
        temp = np.linalg.norm(point1 - point2)
        if (temp <= dist):  # IF the temp euclidean distance is lower than the alread set it will:
            dist = temp  # set the new distance to temp and...
            resultZip = str(usZips["Zip"][i])  # will save the zip that has the same index as the new temp
            # p1=float(myFile["Latitude"][58435])
            # p2=float(myFile["Longitude"][58435])
        i += 1

我知道谷歌也有一个反向地理编码器 API,但它有每天的请求限制。调用的文件myFile是一个 csv 文件,其属性为 userId、纬度、经度、时间戳,大约有一百万个条目。文件 usZips 是公共数据集,包含有关城市、纬度、经度、邮政编码和时区的信息,在美国有大约 43k 条邮政编码记录。

标签: pythonoptimizationvectorizationreverse-geocoding

解决方案


我不知道你的myFile样子usZips(我无法验证代码)。所以,在矢量化的框架中尝试这样的事情:

your_needed_dist = 10 # for example
lat = float(usZips["Latitude"][0])
lon = float(usZips["Longitude"][0])

lat0 = np.array(myFile["Latitude"])
lon0 = np.array(myFile["Longitude"])
dist = np.sqrt((lat-lat0)**2 - (lon-lon0)**2)

condition = dist <= your_needed_dist

# get index (or indices) that satisfy dist <= your_needed_dist
np.argwhere(condition)

# or
resultsZip = str(usZips["Zip"][condition])

还要检查我的代码中距离的定义(这是你需要的还是不需要的)。


推荐阅读