使用df1中的一行之间的经度和纬度查找距离,并对df2中的所有行运行该距离,然后显示最小距离

2024-06-17 08:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,df1包含所有医院的经度和纬度,df2包含城市的经度和纬度。我想找出所有城市之间每家医院的距离,以确定哪家医院离城市最近

样本值

 df1
 hos   lng   lat
 hos1   2     3
 hos2   1     4
 hos3   2     1

 df2
 city  lng   lat
 cit1   5     3
 cit2   6     3
 cit3   2     1


 for i in df1:
 #get the distance of all cities with each hospital
 #get distance between two lon and lat

     def distance(lat1, lon1, lat2, lon2):
         p = 0.017453292519943295
         a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
         return 12742 * asin(sqrt(a))

     def closest(data, city):
     return min(data, key=lambda p:distance(city['lat'],city['lon'],p['lat'],p['lon']))

它没有显示任何内容。我应该在这种情况下使用嵌套循环吗?如何打印所有医院和城市的所有距离

比如:

      hos1  hos2  hos3
 cit1  x     x      x
 cit2  x     x      x
 cit3  x     x      x

Tags: 距离citycosdistancedf1londf2lng
1条回答
网友
1楼 · 发布于 2024-06-17 08:29:26

实现这种过程的一个好方法是为每个城市使用queue

例如:

# Priorize
priorities = {}
for city in cities:
    priorities[city] = []
    for hospital in hospitals:
        heappush(priorities[city], (distance(city, hospital), hospital))

# Get the closest hospital for a city
closest = heappop(priorities[your_city])[1]

NB: You define methods that you never call, and you do not store your data in a structure, that's why you don't get anything...

相关问题 更多 >