Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas groupby weighted cumulative sum

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$$
like image 344
Lehyu Avatar asked Jun 07 '17 15:06

Lehyu


1 Answers

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
like image 180
piRSquared Avatar answered Oct 13 '22 10:10

piRSquared