简体   繁体   中英

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. 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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