Numpy中一维阵列的滚动窗口? [英] Rolling window for 1D arrays in Numpy?

查看:53
本文介绍了Numpy中一维阵列的滚动窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以有效地为Numpy中的1D数组实现滚动窗口?

Is there a way to efficiently implement a rolling window for 1D arrays in Numpy?

例如,我有这个纯Python代码段来计算一维列表的滚动标准偏差,其中observations是一维值列表,而n是标准偏差的窗口长度:

For example, I have this pure Python code snippet to calculate the rolling standard deviations for a 1D list, where observations is the 1D list of values, and n is the window length for the standard deviation:

stdev = []
for i, data in enumerate(observations[n-1:]):
    strip = observations[i:i+n]
    mean = sum(strip) / n
    stdev.append(sqrt(250*sum([(s-mean)**2 for s in strip])/(n-1)))

是否有一种方法可以在Numpy内完全做到这一点,即没有任何Python循环?标准偏差对于numpy.std而言微不足道,但是滚动窗口部分完全使我难过.

Is there a way to do this completely within Numpy, i.e., without any Python loops? The standard deviation is trivial with numpy.std, but the rolling window part completely stumps me.

我找到了博客文章,内容涉及滚动Numpy中的窗口,但似乎不适用于一维数组.

I found this blog post regarding a rolling window in Numpy, but it doesn't seem to be for 1D arrays.

推荐答案

只使用博客代码,但是将函数应用于结果即可.

Just use the blog code, but apply your function to the result.

numpy.std(rolling_window(observations, n), 1)

您所在的位置(来自博客):

where you have (from the blog):

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

这篇关于Numpy中一维阵列的滚动窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆