【发布时间】:2021-06-28 23:58:42
【问题描述】:
我是python新手,所以请原谅我的新手。 我有两个数据集,一个有 440k 行(文件 A),另一个有 10k 行(文件 B)。每个文件都有一对纬度和经度。我试图找到文件 A 中的每个坐标与文件 me 中的每个坐标之间的半正弦距离,然后将其保存到具有 lat1、long1、lat2、long2、距离行的输出文件中。虽然我检查了现有的 for 循环问题,但我不太了解避免嵌套 for 循环的解决方案。所以我使用了以下代码:
##### Opening new csv file and writing headers #####
with open("distance.csv","w+") as file:
csv_writer = writer(file)
row=['lat1', 'long1', 'lat2', 'long2', 'distance']
csv_writer.writerow(row)
#### iterate through each row and calculate the haversine distance ####
for i in range(len(df1)) :
for j in range(len(df2)):
distance = haversine(df1.loc[i, "long1"], df1.loc[i,"lat1"], df2.loc[j, "long2"], df2.loc[j,"lat2"])
with open("distance.csv","a+") as file:
csv_writer = writer(file)
row=[df1.loc[i, "long1"], df1.loc[i,"lat1"], df2.loc[j, "long2"], df2.loc[j,"lat2"], distance]
csv_writer.writerow(row)
这种方法非常耗时。有更好的方法吗?
【问题讨论】:
-
您可以先打开文件一次,无需打开,然后关闭它,以便在下一个循环中再次打开它。首先打开文件,获取您的 csv_writer,然后执行其余的循环
-
感谢这在一定程度上有助于减少运行时间。但是,它仍然需要很长时间。还有其他方法吗?还有,完成执行需要多长时间?
-
你真的需要完整的距离吗?或就在半径或最近的 K 范围内
-
我需要5公里范围内的坐标
-
在这种情况下,您想使用 sklearn Balltree。有关示例,请参阅stackoverflow.com/questions/63121268/…。如果卡住/有问题,请告诉我
标签: python performance for-loop