方法#1
我们可以利用基于np.lib.stride_tricks.as_strided 的scikit-image's view_as_windows 来获得滑动窗口。 More info on use of as_strided based view_as_windows.
from skimage.util.shape import view_as_windows
def create_time_lagged_viewaswindows(X, shift, step):
a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
windows_ar = view_as_windows(a_ext,shift)[:len(X)-shift+step+1:step].T
return pd.DataFrame(windows_ar)
一点解释: 基本思想是我们用零填充尾部,然后创建滑动窗口。要创建窗口,我们使用np.lib.stride_tricks.as_strided 或skimage.util.view_as_windows。
示例运行 -
In [166]: X = pd.Series(range(5))
In [167]: create_time_lagged_viewaswindows(X, shift=4, step=1)
Out[167]:
0 1 2
0 0 1 2
1 1 2 3
2 2 3 4
3 3 4 0
In [168]: create_time_lagged_viewaswindows(X, shift=4, step=2)
Out[168]:
0 1
0 0 2
1 1 3
2 2 4
3 3 0
方法 #2
我们还可以使用np.lib.stride_tricks.as_strided,这需要我们手动设置步幅并使用它来塑造 arg,但我们会避免使用早期方法的转置,这可能值得额外的性能提升。实现看起来像这样 -
def create_time_lagged_asstrided(X, shift, step):
a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
strided = np.lib.stride_tricks.as_strided
s = a_ext.strides[0]
ncols = (len(X)-shift+2*step)//step
windows_ar = strided(a_ext, shape=(shift,ncols), strides=(s,step*s))
return pd.DataFrame(windows_ar)
大型阵列的计时 -
In [215]: X = pd.Series(range(10000))
# Original solution
In [216]: %timeit creat_time_lagged(X, shift=10, step=5)
1 loop, best of 3: 608 ms per loop
# Approach #1
In [217]: %timeit create_time_lagged_viewaswindows(X, shift=10, step=5)
10000 loops, best of 3: 146 µs per loop
# Approach #2
In [218]: %timeit create_time_lagged_asstrided(X, shift=10, step=5)
10000 loops, best of 3: 104 µs per loop