方法#1: 使用broadcasting
def broadcasting_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 return a[S*np.arange(nrows)[:,None] + np.arange(L)]
方法2:使用更有效的方法NumPy strides
def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 n = a.strides[0] return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
样品运行
In [143]: aOut[143]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])In [144]: broadcasting_app(a, L = 5, S = 3)Out[144]: array([[ 1, 2, 3, 4, 5], [ 4, 5, 6, 7, 8], [ 7, 8, 9, 10, 11]])In [145]: strided_app(a, L = 5, S = 3)Out[145]: array([[ 1, 2, 3, 4, 5], [ 4, 5, 6, 7, 8], [ 7, 8, 9, 10, 11]])



