Numpyndarrayのローリングウィンドウ操作



Numpy Ndarrays Rolling Window Operation



(このメモは完全には完成していません)
テスト例を追加する必要があります

パンダのローリングのような、ゴツゴツした配列でのスライディングウィンドウ操作



スライディングウィンドウを生成する

# ---------------------- Numpy array rolling window operation --------------- # Simple operation If it is a pandas, it will be converted to pandas and processed faster. def rolling_window(a, window, axis=0): ''' Return the array of the 2D array sliding window array ''' if axis == 0: shape = (a.shape[0] - window +1, window, a.shape[-1]) strides = (a.strides[0],) + a.strides a_rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) elif axis==1: shape = (a.shape[-1] - window +1,) + (a.shape[0], window) strides = (a.strides[-1],) + a.strides a_rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) return a_rolling

テスト:

機能を適用する

# For the functions that come with pandas DataFrame, for large dimensions, or pandas rolling method # Array, this method is fast # The above is fast, all can be ten times faster than the ratio. def rolling_mean(A, window=None): ret = np.full(A.shape, np.nan) A_rolling = rolling_window(A, window=window, axis=0) Atmp = np.stack(map(lambda x:np.mean(x, axis=0), A_rolling)) ret[window-1:,:] = Atmp return ret def rolling_nanmean(A, window=None): ret = np.full(A.shape, np.nan) A_rolling = rolling_window(A, window=window, axis=0) Atmp = np.stack(map(lambda x:np.nanmean(x, axis=0), A_rolling)) ret[window-1:,:] = Atmp return ret

参照接続: