def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
print shape
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def test_rolling_window(winsize=3):
import time
t = time.clock()
observations = np.random.randn(1000)
np.std(rolling_window(observations, winsize), 1)
print "strided %.6f secs"%(time.clock()-t)
t = time.clock()
for idx in xrange(winsize, len(observations)):
np.std(observations[idx-winsize: idx])
print "loop %.6f secs"%(time.clock()-t)
原理在此篇文章當中有詳細的描述 :
http://chintaksheth.wordpress.com/2013/07/31/numpy-the-tricks-of-the-trade-part-ii/