首页 > 解决方案 > 需要帮助优化此代码以获得更快的结果

问题描述

为了概述数据,有多行数据具有相同的 id,此外,还有多列具有相同的值。现在有一些函数将为具有相同id. 因此,我按 this 分组id,执行我需要对它们执行的功能,然后我开始遍历每个组中的每一行,以执行对每一行产生不同结果的功能,即使具有相同的 id。

以下是一些示例数据:


id  map_sw_lon  map_sw_lat  map_ne_lon  map_ne_lat exact_lon exact_lat
1     10        15           11            16          20       30
1     10        15           11            16          34       50
2     20        16           21            17          44       33
2     20        16           21            17          50       60

这是我的代码:

for id, group in df.groupby("id", sort=False):

   viewport = box(group["map_sw_lon"].iloc[0], 
   group["map_sw_lat"].iloc[0], group["map_ne_lon"].iloc[0], 
   group["map_ne_lat"].iloc[0])
   center_of_viewport = viewport.centroid
   center_hex = h3.geo_to_h3(center_of_viewport.y, center_of_viewport.x, 8)    

# everything above here can be done only once per group.   

# everything below needs to be done per row per group.
   for index, row in group.iterrows():

      current_hex = h3.geo_to_h3(row["exact_lat"], row["exact_lon"], 8)
      df.at[index,'hex_id'] = current_hex
      df.at[index, 'hit_count'] = 1

      df.at[index, 'center_hex'] = center_hex 
      distance_to_center = h3.h3_distance(current_hex, center_hex)
      df.at[index,'hex_dist_to_center'] = distance_to_center

对于 100 万行数据,此代码在大约 5 分钟内工作。问题是我正在处理比这大得多的数据,并且需要一些运行速度更快的东西。我知道不建议在 Pandas 中使用 for 循环,但我不确定如何在不使用它们的情况下解决这个问题。任何帮助,将不胜感激。

编辑:仍在为此苦苦挣扎..任何帮助将不胜感激!

标签: pythonpandasalgorithm

解决方案


您需要进行一些分析以查看代码的每个部分需要多少时间才能运行。我猜想最耗时的部分是geo_to_h3andh3_distance调用。如果是这样,对数据框操作的其他可能改进(例如,使用DataFrame.applyand GroupBy.transform)将无济于事。


推荐阅读