python - 如何将矢量化函数应用于 numpy 数组的前一个元素?

标签 python arrays numpy vectorization

我想应用这样的函数:

s[i] = a*x[i] + (1 - a)*s[i-1]

其中 sx 都是相同长度的数组。

我不想使用 for 循环,因为这些数组非常大 (>5000 万)。我试过做这样的事情

def f(a,x):
    s = [0]*len(x)
    s[i] = a*x[i] + (1 - a)*s[i-1]
    return s

当然 i 没有定义,所以这行不通。

有没有办法使用 mapnumpy.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/

相关文章:

通过字典中的后代元素进行过滤的 Pythonic 方式

python - 即使存在缺失数据,如何重组 Pandas 数据框

python - 在 Python 中导入 PIL (Pillow) 模块

javascript - 在非结构化对象数组中查找不同键的数量

javascript - 检查一个数组中的每个元素是否都在第二个数组中

c# - 将 2D 列表转换为 2D 字符串数组 C#

python - Anaconda Python - 如何重新安装 NumPy

python - 从 psycopg2 connection.commit() 获取受影响的行数

python - 将 3D 矩阵转换为垂直级联的 1D 数组

python - 将风向分为几类