【问题标题】:Stuck in nested for loop in python卡在python中的嵌套for循环中
【发布时间】: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


【解决方案1】:

如前所述,输出只能打开一次。 这个算法是O(NxM),你不能做太多,但是通过一些技巧,它可以运行得更快。 简单的解决方案可以是使用 itertools.product 创建所有需要的组合并分成块,并在多进程解决方案中使用类似的代码解决。这是an example。 困难的解决方案是找到解决问题的另一种方法,如果有一些近似值可用,您可以尝试减少数据集,创建类似协调的集群。

【讨论】:

  • OP 在 cmets 中有更具体的问题;并对半径内的位置感兴趣。对于这一点,有一些算法可以防止循环。
猜你喜欢
  • 2020-10-09
  • 2020-06-08
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 2017-06-05
  • 2018-08-12
相关资源
最近更新 更多