Padding Numpy Rolling Window Operations Using Strides
I have a function f that I would like to efficiently compute in a sliding window. def efficient_f(x): # do stuff wSize=50 return another_f(rolling_window_using_strides(x,
Solution 1:
Here's one way to solve it with np.lib.stride_tricks.as_strided
-
def strided_axis0(a, fillval, L): # a is 1D array
a_ext = np.concatenate(( np.full(L-1,fillval) ,a))
n = a_ext.strides[0]
strided = np.lib.stride_tricks.as_strided
returnstrided(a_ext, shape=(a.shape[0],L), strides=(n,n))
Sample run -
In [95]: np.random.seed(0)
In [96]: a = np.random.rand(8,1)
In [97]: a
Out[97]:
array([[ 0.55],
[ 0.72],
[ 0.6 ],
[ 0.54],
[ 0.42],
[ 0.65],
[ 0.44],
[ 0.89]])
In [98]: strided_axis0(a[:,0], fillval=np.nan, L=3)
Out[98]:
array([[ nan, nan, 0.55],
[ nan, 0.55, 0.72],
[ 0.55, 0.72, 0.6 ],
[ 0.72, 0.6 , 0.54],
[ 0.6 , 0.54, 0.42],
[ 0.54, 0.42, 0.65],
[ 0.42, 0.65, 0.44],
[ 0.65, 0.44, 0.89]])
Post a Comment for "Padding Numpy Rolling Window Operations Using Strides"