汎用:より良いavgを移動
import numpy as np
from numpy.lib.stride_tricks import as_strided
def moving_slice(a, k):
a = a.ravel()
return as_strided(a, (a.size - k + 1, k), 2 * a.strides)
:
def moving_avg(a, k):
ps = np.cumsum(a)
return (ps[k-1:] - np.r_[0, ps[:-k]])/k
例:
a = np.arange(10)
moving_avg(a, 4)
# array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5])
ms = moving_slice(a, 4)
ms
# array([[0, 1, 2, 3],
# [1, 2, 3, 4],
# [2, 3, 4, 5],
# [3, 4, 5, 6],
# [4, 5, 6, 7],
# [5, 6, 7, 8],
# [6, 7, 8, 9]])
# no data are copied:
a[4] = 0
ms
# array([[0, 1, 2, 3],
# [1, 2, 3, 0],
# [2, 3, 0, 5],
# [3, 0, 5, 6],
# [0, 5, 6, 7],
# [5, 6, 7, 8],
# [6, 7, 8, 9]])
ニース、私はそれらにRTFMする瞬間を与えて... :) –
非常に答えに感謝します!それは超賢いです –