Numpy version of rolling MAD (mean absolute deviation)

扶醉桌前 提交于 2019-12-10 18:04:19

问题


How to make a rolling version of the following MAD function

from numpy import mean, absolute

def mad(data, axis=None):
    return mean(absolute(data - mean(data, axis)), axis)

This code is an answer to this question

At the moment i convert numpy to pandas then apply this function, then convert the result back to numpy

pandasDataFrame.rolling(window=90).apply(mad) 

but this is inefficient on larger data-frames. How to get a rolling window for the same function in numpy without looping and give the same result?


回答1:


Here's a vectorized NumPy approach -

# From this post : http://stackoverflow.com/a/40085052/3293881
def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))

# From this post : http://stackoverflow.com/a/14314054/3293881 by @Jaime
def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

def mad_numpy(a, W):
    a2D = strided_app(a,W,1)
    return np.absolute(a2D - moving_average(a,W)[:,None]).mean(1)

Runtime test -

In [617]: data = np.random.randint(0,9,(10000))
     ...: df = pd.DataFrame(data)
     ...: 

In [618]: pandas_out = pd.rolling_apply(df,90,mad).values.ravel()
In [619]: numpy_out = mad_numpy(data,90)

In [620]: np.allclose(pandas_out[89:], numpy_out) # Nans part clipped
Out[620]: True

In [621]: %timeit pd.rolling_apply(df,90,mad)
10 loops, best of 3: 111 ms per loop

In [622]: %timeit mad_numpy(data,90)
100 loops, best of 3: 3.4 ms per loop

In [623]: 111/3.4
Out[623]: 32.64705882352941

Huge 32x+ speedup there over the loopy pandas solution!



来源:https://stackoverflow.com/questions/42865103/numpy-version-of-rolling-mad-mean-absolute-deviation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!