Xarray具有权重的滚动平均值 [英] Xarray rolling mean with weights

查看:208
本文介绍了Xarray具有权重的滚动平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用numpy的权重进行滚动/滚动平均时,例如做这样的事情:

data = np.random.random(100)  # Example data...
weights = np.array([1, 2, 1])
data_m = np.convolve(data, weights/float(np.sum(weights)), "same")

然后将data_m [0]和data_m [-1]替换为例如nans,取决于应用程序.

xarray可以完成类似的操作.我要做的(在这种情况下)是

xr.DataArray(data).rolling(dim_0=3, center=True).mean(dim="dim_0")

但这对应于权重

weights = np.array([1, 1, 1])

在numpy示例中为

.使用xarray时,我将如何应用其他权重?

解决方案

xarray中尚未实现weighted-rolling-mean.

以下内容几乎可以完成相同的操作,但是速度会很慢. 我认为使用np.convolve是当前的最佳选择.

def weighted_sum(x, axis):
    weight = [1, 2, 1]
    if x.shape[axis] == 3:
        return np.sum(x * weight, axis=axis)
    else:
        return np.nan

da.rolling(dim_0=3, center=True).reduce(weighted_sum)

当前,我们正在努力支持更灵活(更快)的滚动操作.参见 https://github.com/pydata/xarray/pull/1837

使用xarray = 0.10.2时,加权滚动平均值可以计算如下,

weight = xr.DataArray([0.25, 0.5, 0.25], dims=['window'])
da.rolling(dim_0=3, center=True).construct('window').dot(weight)

where construct方法构造滚动对象的视图,其中窗口尺寸(在上例中为window)被附加到最后一个位置. 权重数组的内部乘积给出沿窗口尺寸的加权总和.

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, 2, 1])
data_m = np.convolve(data, weights/float(np.sum(weights)), "same")

And then replace data_m[0] and data_m[-1] with e.g. nans, depending on application.

Something alike can be done with xarray. What I do (in this case) is

xr.DataArray(data).rolling(dim_0=3, center=True).mean(dim="dim_0")

But this corresponds to the weights

weights = np.array([1, 1, 1])

in the numpy example. How would I apply other weights, when using xarray?

解决方案

The weighted-rolling-mean is not yet implemented in xarray.

The following does almost the same thing but it would be quite slow. I think the use of np.convolve is the current best choice.

def weighted_sum(x, axis):
    weight = [1, 2, 1]
    if x.shape[axis] == 3:
        return np.sum(x * weight, axis=axis)
    else:
        return np.nan

da.rolling(dim_0=3, center=True).reduce(weighted_sum)

Currently, we are working to support more flexible (and faster) rolling operations. See https://github.com/pydata/xarray/pull/1837

EDIT:

With xarray=0.10.2, weighted rolling mean can be computed as follows,

weight = xr.DataArray([0.25, 0.5, 0.25], dims=['window'])
da.rolling(dim_0=3, center=True).construct('window').dot(weight)

where construct method constructs a view of the rolling object, where the window dimension (named window in the above example) is attatched to the last position. inner product with the weight array gives the weighted sum along the window dimension.

这篇关于Xarray具有权重的滚动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆