我想应用这样的函数:
s[i] = a*x[i] + (1 - a)*s[i-1]
其中 s
和 x
都是相同长度的数组。
我不想使用 for 循环,因为这些数组非常大 (>5000 万)。我试过做这样的事情
def f(a,x):
s = [0]*len(x)
s[i] = a*x[i] + (1 - a)*s[i-1]
return s
当然 i
没有定义,所以这行不通。
有没有办法使用 map
或 numpy.apply_along_axis
或其他一些矢量化方法来做到这一点?
我还没有遇到一种方法可以在不使用 for 循环的情况下将函数应用于数组的当前和先前元素,而这正是我在这里真正想了解的方法。
编辑
为了明确起见,这里是 for 循环实现,它可以工作但我想避免
s = [0]*len(x)
a=0.45
for i in range(len(x)):
s[i] = a*x[i] + (1-a)*s[i-1]
s[0] = x[0] # reset value of s[0]
最佳答案
正如我在 answer to basically the same question 中所写,你不能:
There is no other way (in general) except for an explicit
for
loop. This is because there is no way to parallelize this task across the rows (since every row depends on some other row).What makes this even harder is that you can easily generate chaotic behavior, for example with the seemingly innocent looking logistic map:
x_{n+1} = r * x_n * (1 - x_{n-1})
.You can only find a way around this if you manage to find a closed form, essentially eliminating the recurrence relation. But this has to be done for each recurrence relation and I am pretty sure you are not even guaranteed that a closed form exists...
关于python - 如何将矢量化函数应用于 numpy 数组的前一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032767/