问题
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 depreciated now. How would you change this to work under current functionality.
Thank you.
回答1:
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.
来源:https://stackoverflow.com/questions/50744746/follow-up-rolling-apply-depreciated