首页 > 解决方案 > 计算 2 个不同文件中多个点之间的两个位置的距离

问题描述

import pandas as pd
import numpy as np
from geopy import distance
#Import all the files
shop_loc=pd.read_excel('locations.xlsx')
comp_loc=pd.read_excel('locations_comp.xlsx')
#convert the coordinates of both the files to a tuple list for the geopy to read the distance 
shop_loc['coor']=list(zip(shop_loc.Lat,shop_loc.Lon))
comp_loc['coor']=list(zip(comp_loc.Long,comp_loc.Long))
#Function for the calculation of two points
def distance_from(loc1,loc2): 
    dis = distance.distance(loc1, loc2).miles
    return round(dis,2)
#Calculate the distance of one shop location to competitor shop location
for _,row in comp_loc.iterrows():
    shop_loc[row.Comp]=shop_loc['coor'].apply(lambda x: distance_from(row.coor,x))

我在两个不同的文件中有 62 家不同的商店和 8 个不同的竞争对手。我试图找出每家商店与所有 8 家不同竞争对手商店的距离。当我单独进行测试时,我得到了正确的位置。但只要我把这段代码拿出来。我得到非常不同的距离值。

例如 Shop_location =(40.583639,-75.458446) Competitor_location = (40.049580,-75.086617) 在我编写的函数中,我得到了几乎超过 7900 英里的距离,但是手动测试距离给我的距离是 41.75。谁能帮我解决我哪里出错了

标签: pythonfunctiondistancegeopy

解决方案


嘿尝试这样的事情:

import pandas as pd
import numpy as np
from geopy.distance import geodesic 
#Import all the files
shop_loc=pd.read_excel('locations.xlsx')
comp_loc=pd.read_excel('locations_comp.xlsx')
#convert the coordinates of both the files to a tuple list for the geopy to read the distance 
shop_loc['coor']=list(zip(shop_loc.Lat,shop_loc.Lon))
comp_loc['coor']=list(zip(comp_loc.Long,comp_loc.Long))
#Function for the calculation of two points
def distance_from(loc1,loc2): 
    dis = geodesic(loc1, loc2).miles
    return round(dis,2)
#Calculate the distance of one shop location to competitor shop location
for _,row in comp_loc.iterrows():
    shop_loc[row.Comp]=shop_loc['coor'].apply(lambda x: distance_from(row.coor,x))

推荐阅读