首页 > 解决方案 > python - 如何在numpy中应用熊猫滚动?

问题描述

我想将pandas.rolling(window).apply(func)范例应用于 numpy 数组。在搜索时遇到了 numpy 的这个函数。这就是我用它做的。

def rolling_apply(fun, a, w):
    r = np.empty(a.shape)
    r.fill(np.nan)
    for i in range(w - 1, a.shape[0]):
        r[i] = fun(a[(i-w+1):i+1])
    return r

def test(x):
    return x.sum()

arr=np.random.rand(20)
e=rolling_apply(test,arr,10)

运行时出现此错误

ValueError:使用序列设置数组元素。

你能告诉我为什么会发生这个错误吗

编辑:

这工作我在上面的代码中犯了一个初始错误。这是有效的

标签: pythonpandasnumpy

解决方案


数组形状和索引有点混乱。快速解决:

def rolling_apply(fun, a, w):
r = np.empty((a.shape[0]-w+1, w))
r.fill(np.nan)
for i in range(w - 1, a.shape[0]):
    r[i-w+1] = fun(a[(i-w+1):i+1])
return r

def test(x):
    return x*2

arr=np.random.rand(20)
e=rolling_apply(test,arr,10)

推荐阅读