【问题标题】:python code speed up nested for loops with two dataframespython代码使用两个数据帧加速嵌套for循环
【发布时间】:2021-12-31 01:18:43
【问题描述】:

ServicePop 有 x、y 坐标,我想添加一个平方数(gid)。 我做了一个嵌套的 for 循环来分配一个平方数,但 ServicePop 太大了,需要几个小时。 有没有更快更有效的方法来做到这一点? 当我在谷歌搜索时,他们说使用数据框或矢量化的应用会有所帮助,但我无法更改我的代码以使用这种改进。
我需要你的帮助。

import pandas
import datetime
TotPopCenter = pandas.read_csv('TotalPopulationCurrentCenterShapeCoordinate_UTF8.csv', encoding='euckr')
ServicePop = pandas.read_csv('202101_Final.csv', encoding='euckr')
ServicePop.insert(9,'gid','')
Service_gid = ['' for _ in range(len(ServicePop))]
for j in range(len(ServicePop)):
    for i in range(len(TotPopCenter)):
        if (ServicePop['X_COORD'][j] >= TotPopCenter['xcoord'][i]-125) and \
           (ServicePop['X_COORD'][j] < TotPopCenter['xcoord'][i]+125) and \
           (ServicePop['Y_COORD'][j] >= TotPopCenter['ycoord'][i]-125) and \
           (ServicePop['Y_COORD'][j] < TotPopCenter['ycoord'][i]+125):
           Service_gid[j] = TotPopCenter['gid'][I]
ServicePop['gid'] = Service_gid

TotPopCenter gid lbl val xcoord ycoord 0 LM87ab60ba 南南 1087375 1760625 服务流行 STD_YMD X_COORD Y_COORD HCODE WKDY_CD TIME HPOP WPOP VPOP 0 2021-01-01 1.087484e+06 1.760579e+06 2207061 周五 0 27.97 0.82 7.24

【问题讨论】:

    标签: python dataframe performance vectorization nested-for-loop


    【解决方案1】:

    如果您希望专门优化嵌套循环,您可能希望使用itertools.product,使用:

    import itertools
    for j, i in itertools.product(range(len(ServicePop)), range(len(TotPopCenter))):
    

    而不是:

    for j in range(len(ServicePop)):
        for i in range(len(TotPopCenter)):
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 2021-04-27
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多