Peslier53
Peslier53

Reputation: 619

pandas rolling cumulative weighted average

I am trying to compute a rolling cumulative weighted average.

df["cum_wt_avg"] = df['val'].mul(df['wt']).cumsum().div(df['wt'].cumsum())

This gives me the cumulative weighted average. How can i do to apply the same function rolling with a period of 2 for instance?

df :
   val       wt  
1  100       2
2  300       3
3  200       5

required df :

   val       wt  cum_wt_avg    rolling_cum_wt_avg_2periods
1  100       2     100               100
2  300       3     220               220
3  200       5     210               237.5 

Upvotes: 0

Views: 39

Answers (1)

not_speshal
not_speshal

Reputation: 23166

Just use rolling with the same operations:

df["rolling_cum_wt_avg_2periods"] = df["val"].mul(df["wt"]).rolling(2, min_periods=1).sum().div(df["wt"].rolling(2, min_periods=1).sum())

>>> df
   val  wt  rolling_cum_wt_avg_2periods
0  100   2                        100.0
1  300   3                        220.0
2  200   5                        237.5

Upvotes: 2

Related Questions