【问题标题】:Need help optimizing this code for faster results需要帮助优化此代码以获得更快的结果
【发布时间】:2019-07-12 17:09:39
【问题描述】:

为了给出数据的概览,多行数据具有相同的 id,此外,还有多列具有相同的值。现在有一些函数将为具有相同id 的行输出相同的结果。因此,我按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 循环,但我不知道如何在不使用它们的情况下解决这个问题。任何帮助,将不胜感激。

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

【问题讨论】:

  • 这是您无与伦比的智能报价。
  • 你的代码中的 h3 是什么?
  • @jottbe eng.uber.com/h3
  • (代码 sn-ps 中的红色代码着色器只是一个 JavaScript 语法着色器。它并不总是正确,但在这里看起来不错)。
  • 你有没有试过为geo_to_h3h3_distance 的函数调用计时?这两个函数调用花费了总执行时间的百分比是多少?

标签: python pandas algorithm


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 2022-09-30
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多