【问题标题】:How do I vectorize a pandas iterrows loop如何矢量化 pandas iterrows 循环
【发布时间】:2019-12-21 20:06:03
【问题描述】:

我有一个大数据框,我需要遍历它。但是,非常大的数据帧需要很长时间。我知道 iterrows 很慢,而矢量化要快得多。但是,我不知道如何重写 iterrows 循环。

我的数据框如下:

print(df_toe.head(10))

 z_toe  dn50_toe  Nod  ht/h  output_ok
0   -3.5  0.067171  NaN   NaN        1.0
1   -3.5  0.082472  NaN   NaN        1.0
2   -3.5  0.095543  NaN   NaN        1.0
3   -3.5  0.196341  NaN   NaN        1.0
4   -3.5  0.232024  NaN   NaN        1.0
5   -3.5  0.347270  NaN   NaN        1.0
6   -3.5  0.353661  NaN   NaN        1.0
7   -3.5  0.404841  NaN   NaN        1.0
8   -3.5  0.632502  NaN   NaN        1.0
9   -3.5  0.922923  NaN   NaN        1.0

加上一些额外的参数:

z_bed = -4.5 
swl = 1.8

遍历数据帧df_toe的iterrows循环写法如下:

def dftoe_det_2nd(df_toe):

    for i in df_toe.index:
        'Define input variables'
        z_toe = df_toe.get_value(i,'z_toe')
        dn50_toe = df_toe.get_value(i,'dn50_toe')

        'Define restrictions between which it can operate for z_toe/h'
        h = swl - z_bed
        ht = swl - z_toe
        df_toe.set_value(i,'ht/h',abs(ht / h))

        if z_toe < z_bed:
            df_toe.set_value(i,'output_ok',0)

        'Show all waterheights'
        df_toe.set_value(i,'Nod',Nodtoe())

        if 0.90 < abs(ht / h) or 0.4 > abs(ht / h):
            df_toe.set_value(i,'output_ok',0)

        if h > 25:
            df_toe.set_value(i,'output_ok',0)

    df_toe = df_toe[df_toe['output_ok'] == 1]
    del df_toe['output_ok']
    return df_toe

有谁知道如何在速度和计算时间方面进行优化?

【问题讨论】:

    标签: python pandas loops dataframe vectorization


    【解决方案1】:

    您可以关注https://stackoverflow.com/a/28490706/3528612 并在循环中尝试 openmp。或者,如果您有资源,即更多处理器,您可以尝试 mpi4py 并将循环并行化为小块以使其更快

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2017-03-13
      • 1970-01-01
      • 2017-09-26
      • 2015-01-02
      • 2021-04-06
      • 2016-09-28
      • 2012-09-24
      • 2021-01-18
      相关资源
      最近更新 更多