简体   繁体   English

熊猫的加权移动平均线-难以实施

[英]weighted moving average in pandas - having trouble implementing

I have a one-dimensional time series (below), created using pandas. 我有一个使用熊猫创建的一维时间序列(下)。 that I'm having trouble creating a weighted moving average for. 我在为其创建加权移动平均值时遇到了麻烦。 I've seen others have come across this problem in pandas but there doesn't seem to be a consensus solution from what I've read. 我已经看到其他人在大熊猫中遇到了这个问题,但是根据我所读的内容,似乎还没有达成共识的解决方案。

1899    0.780
1900    -3.278
1901    1.096
1902    0.578
1903    4.608
1904    4.208
1905    -0.416
1906    1.392
1907    5.242
1908    2.922
1909    1.696
1910    2.984
1911    3.882
1912    0.536
1913    0.512
1914    0.170
1915    1.554
1916    3.936
1917    3.256
1918    1.404
... ...

The code I'm currently using is below, using weights (1-3-5-6-5-3-1), but I'm not getting accurate results. 我当前使用的代码如下,使用权重(1-3-5-6-5-3-1),但是我没有得到准确的结果。 Any help would be appreciated. 任何帮助,将不胜感激。

wts = np.array([1, 3, 5, 6, 5, 3, 1])
def f(w):                        
         def g(x):
            return (w*x).mean()
        return g
anom_winter_av_npi.rolling(window=7).apply(f(wts))

I think your weighted average function may be wrong (the code looks ok). 我认为您的加权平均函数可能是错误的(代码看起来还可以)。 Try: 尝试:

# use the .dot method for shortness' sake
anom_winter_av_npi.rolling(window=7).apply(lambda x: wts.dot(x) / wts.sum())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM