如何使用pd.rolling或pd.ewm实现Pandas自定义指数衰减计算
解决方案
核心原理
你需要的递推公式x[t] = a[t] + x[t-1] * exp(-alpha)本质是输入序列与指数衰减核的线性卷积,完全可以用向量运算实现,无需显式for循环,性能远高于Python原生循环,适合大数据量场景。
方案1:numpy卷积实现(性能最优)
import pandas as pd import numpy as np # 示例数据 df = pd.DataFrame({"a": [1, 0, 0, 2, 0]}) alpha = 0.5 # 自定义衰减参数 decay = np.exp(-alpha) # 构造指数衰减核 kernel = np.power(decay, np.arange(len(df))) # 卷积计算后取对应长度的结果 result_arr = np.convolve(df['a'], kernel)[:len(df)] # 若需要初始值设为nan,取消注释下一行 # result_arr[0] = np.nan # 转换为DataFrame newdf = pd.DataFrame(result_arr, columns=['result'])
方案2:pd.ewm实现(符合pandas内置工具需求)
# 接上述参数定义 decay = np.exp(-alpha) # adjust=False启用递归计算模式,结果乘以(1-decay)匹配你的计算规则 new_series = df['a'].ewm(alpha=1-decay, adjust=False).mean() * (1 - decay) newdf = new_series.to_frame(name='result')
效果验证
以alpha = np.log(2)(即decay=0.5)为例,输出结果为:
| index | result |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.25 |
| 3 | 2.125 |
| 4 | 1.0625 |
完全匹配你给出的计算规则。
内容的提问来源于stack exchange,提问作者Hedgehog
相关产品推荐
相关产品推荐

