A | B | B_new
----| ---- |---------
1 | 1 | 1
1 | 2 | 1.5
1 | 3 | 2.25
2 | 2 | 2
2 | 4 | 3
2 | 6 | 4.5
I have a dataframe, and I want to calculate weighted cumulative sum of B group by A. But I don't know how to apply the transformation.
$$new = C*cur+(1-C)*old$$
You want to apply
exponentially weighted moving average within a groupby
df.assign(
B_new=df.groupby('A').B.apply(
lambda x: x.ewm(alpha=0.5, adjust=False).mean()
)
)
A B B_new
0 1 1 1.00
1 1 2 1.50
2 1 3 2.25
3 2 2 2.00
4 2 4 3.00
5 2 6 4.50
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With