2

Following up on this answer: Is there a way to do a weight-average rolling sum over a grouping?

rsum = pd.rolling_apply(g.values,p,lambda x: np.nansum(w*x),min_periods=p)

rolling_apply is deprecated now. How would you change this to work under current functionality.

yivi
  • 42,438
  • 18
  • 116
  • 138
user1911092
  • 3,941
  • 9
  • 26
  • 30
  • Check the [docs](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0180-api) it has been deprecated since `0.18.0` – EdChum Jun 07 '18 at 15:16

1 Answers1

2

As of 0.18+, use Series.rolling.apply.

w = np.array([0.1,0.1,0.2,0.6])

df.groupby('ID').VALUE.apply(
    lambda x: x.rolling(window=4).apply(lambda x: np.dot(x, w), raw=False))

0       NaN
1       NaN
2       NaN
3     146.0
4     166.0
5       NaN
6       NaN
7       NaN
8       2.5
9       NaN
10      NaN
11      NaN
12     35.5
13     21.4
14      NaN
15      NaN
16      NaN
17      8.3
18      9.8
19      NaN
Name: VALUE, dtype: float64

The raw argument is new to 0.23 (set it to specify passing Series v/s arrays), so remove it if you're having trouble on older versions.

cs95
  • 379,657
  • 97
  • 704
  • 746