简体   繁体   English

大熊猫群加权累积和

[英]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. 我有一个数据帧,我想用A计算B组的加权累积和。但我不知道如何应用转换。

$$new = C*cur+(1-C)*old$$

You want to apply exponentially weighted moving average within a groupby 您希望在groupby apply 指数加权移动平均值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM