Python 嵌套循环或函数应用程序
我有2组纬度/经度坐标,共4个阵列。我的目标是找出一组(airbnb_coord)和第二组(station_coord)中最近成员之间的距离。我已经编写了一个嵌套for循环来实现这一点Python 嵌套循环或函数应用程序,python,performance,for-loop,data-science,Python,Performance,For Loop,Data Science,我有2组纬度/经度坐标,共4个阵列。我的目标是找出一组(airbnb_coord)和第二组(station_coord)中最近成员之间的距离。我已经编写了一个嵌套for循环来实现这一点 shortest_distance = make_array() for air_lat, air_long in zip(airbnb_coord[0],airbnb_coord[1]): for stat_lat, stat_long in zip(station_coord[0],station_c
shortest_distance = make_array()
for air_lat, air_long in zip(airbnb_coord[0],airbnb_coord[1]):
for stat_lat, stat_long in zip(station_coord[0],station_coord[1]):
distances = make_array()
distances = np.append(distances, np.sqrt(((air_lat-stat_lat)**2)+((air_long-stat_long)**2)))
shortest_distance = np.append(shortest_distance, min(distances))
问题是,airbnb_coord有40000长,station_coord有500长。这已经运行了一个多小时了
谁能告诉我有没有更好的办法?我在函数应用方面很弱,但我相信有一种策略可以使用这种方法。如果不计算每次迭代中的最小距离,可以显著缩短时间
shortest_distance = make_array()
for air_lat, air_long in zip(airbnb_coord[0],airbnb_coord[1]):
min_distance = np.sqrt(((air_lat-station_coord[0][0])**2)+((air_long-station_coord[0][0])**2))
for stat_lat, stat_long in zip(station_coord[0], station_coord[1]):
distance = np.sqrt(((air_lat-stat_lat)**2)+((air_long-stat_long)**2))
if distance < min_distance:
min_distance = distance
shortest_distance = np.append(shortest_distance, min_distance)
shortest_distance=make_array()
对于air_lat,air_long in zip(airbnb_coord[0],airbnb_coord[1]):
最小距离=np.sqrt(((空中站合作[0][0])**2+((空中站合作[0][0])**2))
对于stat_lat,stat_long in zip(station_coord[0],station_coord[1]):
距离=np.sqrt((空气横向-横向)**2)+(空气纵向-纵向)**2))
如果距离小于最小距离:
最小距离=距离
最短距离=np.append(最短距离,最小距离)
请向我们展示一个坐标小样本的输入和(预期)输出。这是您需要多次运行的吗?如果不是,像这样的未优化程序就可以了。不管需要多长时间,都让它运行。(尽管我确实建议使用类似于tqdm
的方法,以便您了解其进度和预期完成时间)。如果您需要多次运行它,那么您需要对其进行优化。我没有这方面的经验,但我看过这段视频,它与这个主题非常相关。虽然不是用python编写的,但是原理是一样的。所以,考虑到所有AirBnB到station对,您想要最短的?这看起来像是上的一个二分变体,通常有次二次算法。作为二分体,可能有一种更有效的算法。凭直觉,如果AirBnB-A在AirBnB-B和Station-A之间,那么AirBnB-B/Station-A就不是答案。在每个Station周围创建一个voronoi图怎么样。然后,距离每个airbnb最近的车站将是其所在的voronoi形状。