python - 需要帮助优化此代码以获得更快的结果

标签 python pandas algorithm

为了给出数据的概览,有多行数据具有相同的 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

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

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

最佳答案

您需要进行一些分析,以了解代码的每个部分运行需要多少时间。我猜想最耗时的部分是 geo_to_h3h3_distance 调用。如果是这样,对数据框操作的其他可能改进(例如,使用 DataFrame.applyGroupBy.transform)将不会有太大帮助。

关于python - 需要帮助优化此代码以获得更快的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57011347/

相关文章:

python - PySpark 对已排序的内容进行排序

python - 在有 GIL 的情况下,您可以在 Python 中竞争条件吗?

python - 朱皮特 : Why does this second command stop the first one from working?

java - 有人知道如何自动在手机屏幕上找到坏点吗?

python-3.x - 将 Pandas 数据框转换为包含 ID 和权重的元组列表

algorithm - 当我知道访问每个元素的所有概率时,我应该使用什么搜索树

对数组进行操作的 Pandas UDF

python - 根据其他列的值创建新列

algorithm - 查找具有最大元素总和/数量的子数组

c - 打印日历月