如何计算滚动/累积指数移动平均?遇ewm不支持expanding数据框报错
解决Expanding对象无法调用ewm()的问题
你遇到的错误是因为pandas中expanding()返回的Expanding对象没有内置的ewm()方法,而mean()是Expanding支持的聚合方法,所以前者能运行后者报错。要计算累积指数移动平均,有两种可行方案:
方案一:直接使用ewm()计算累积EWMA
pandas的ewm()方法本身就是从序列起始位置开始,逐点计算指数加权移动平均,结果等价于累积式的EWMA。示例代码:
# 基础用法 df['cumulative_ewma'] = df['value'].ewm(halflife=.05).mean() # 若需递归式计算(不调整权重),添加adjust=False参数 df['cumulative_ewma'] = df['value'].ewm(halflife=.05, adjust=False).mean()
方案二:自定义函数结合expanding().apply()
如果需要严格基于expanding窗口逻辑计算,可以自定义EWMA函数后通过apply()调用:
import pandas as pd def get_window_ewma(window): return pd.Series(window).ewm(halflife=.05).mean().iloc[-1] df['cumulative_ewma'] = df['value'].expanding(1).apply(get_window_ewma)
注意:这种方法在数据量较大时运行效率较低,优先选择方案一。
内容的提问来源于stack exchange,提问作者greenguy
相关产品推荐
相关产品推荐

