Xarray rolling mean with weights

前端 未结 3 596
执念已碎
执念已碎 2021-01-01 07:46

When I do running / rolling mean with weights in numpy, I e.g. do something like this:

data = np.random.random(100)  # Example data...
weights = np.array([1,         


        
3条回答
  •  长发绾君心
    2021-01-01 08:46

    If you want a Gaussian-like filter, another hack is to apply the rolling mean recursively.

    Infinite recursions of the boxcar filter (i.e., our rolling mean) becomes a Gaussian filter. See B-spline in wikipedia for the detail.

    Example:

    x = xr.DataArray([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], dims=['x'])
    
    # With window=2
    tmp = x
    plt.plot(tmp, '-ok', label='original')
    for i in range(3):
        tmp = tmp.rolling(x=2, min_periods=1).mean()
        plt.plot(tmp, '-o', label='{}-times'.format(i+1))
    plt.legend()
    

    # with window=3, center=True
    tmp = x
    plt.plot(tmp, '--ok', label='original')
    for i in range(3):
        tmp = tmp.rolling(x=3, center=True, min_periods=1).mean()
        plt.plot(tmp, '-o', label='{}-times'.format(i+1))
    plt.legend()
    

    Note: if you want to centralize the result, use the odd window size.

提交回复
热议问题