【python】numpy实现rolling滚动的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/brucewong0516/article/details/84840469

相比较pandas,numpy并没有很直接的rolling方法,但是numpy 有一个技巧可以让NumPy在C代码内部执行这种循环。这是通过添加一个与窗口大小相同的额外尺寸和适当的步幅来实现的。

import numpy as np

data = np.arange(20)

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)

rolling_window(data,10)
Out[12]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [ 3,  4,  5,  6,  7,  8,  9, 10, 11, 12],
       [ 4,  5,  6,  7,  8,  9, 10, 11, 12, 13],
       [ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14],
       [ 6,  7,  8,  9, 10, 11, 12, 13, 14, 15],
       [ 7,  8,  9, 10, 11, 12, 13, 14, 15, 16],
       [ 8,  9, 10, 11, 12, 13, 14, 15, 16, 17],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

np.mean(rolling_window(data,10))
Out[13]: 9.5

np.mean(rolling_window(data,10),-1)
Out[14]: array([ 4.5,  5.5,  6.5,  7.5,  8.5,  9.5, 10.5, 11.5, 12.5, 13.5, 14.5])

猜你喜欢

转载自blog.csdn.net/brucewong0516/article/details/84840469