我想这个小技巧使用strides and as_strided将完成以下工作:
def max_rolling1(a, window,axis =1):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
return np.max(rolling,axis=axis)
为了进行比较,IS 根据您的算法定义了另一个函数:
def max_rolling2(A,K):
rollingmax = np.array([max(A[j:j+K]) for j in range(len(A)-K)])
return rollingmax
和比较timeit
在我的笔记本电脑上是:
with :
A = np.random.rand(100000)
K = 10
%timeit X = max_rolling2(A,K)
170 ms ± 19.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit X = max_rolling1(A,K)
> 3.75 ms ± 479 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)