避免循环的最佳方法

问题描述 投票:0回答:1

我有 2 个相同长度的数字 x 和 y 数据帧以及一个输入数字 a。我想找到计算第三个列表 z 的最快方法,例如:

  • z[0] = a
  • z[i] = z[i-1]*(1+x[i]) + y[i]

不使用这样的循环:

a = 213
x = pd.DataFrame({'RandomNumber': np.random.rand(200)})
y = pd.DataFrame({'RandomNumber': np.random.rand(200)})
z = pd.Series(index=x.index, dtype=float)
z[0] = a
for i in range(1,len(x.index)):
    z[i] = z[i-1]*(1+x.iloc[i]) + y.iloc[i]




python pandas dataframe optimization
1个回答
0
投票

你无法真正向量化这个函数,操作的开发变得太复杂。

正如评论中所建议的,如果速度是一个问题,你可以使用

numba

from numba import jit

def f(a, x, y):
    out = [a]
    for i in range(1, len(x)):
        out.append(out[i-1] * (1 + x[i]) + y[i])
    return out

out = pd.Series(f(213, x['RandomNumber'].to_numpy(), y['RandomNumber'].to_numpy()), index=x.index)

输出(使用

np.random.seed(0)
并有 5 行):

0     213.000000
1     365.772922
2     587.139217
3     908.025165
4    1293.097825
dtype: float64
© www.soinside.com 2019 - 2024. All rights reserved.