如何使用 Pandas 计算加权移动平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9621362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I compute a weighted moving average using pandas
提问by thatshowthe
Using pandas I can compute
使用熊猫我可以计算
- simple moving average SMA using
pandas.stats.moments.rolling_mean - exponential moving average EMA using
pandas.stats.moments.ewma
- 简单的移动平均 SMA 使用
pandas.stats.moments.rolling_mean - 指数移动平均线 EMA 使用
pandas.stats.moments.ewma
But how do I compute a weighted moving average (WMA) as described in wikipedia http://en.wikipedia.org/wiki/Exponential_smoothing... using pandas?
但是我如何计算一个加权移动平均线 (WMA),如维基百科http://en.wikipedia.org/wiki/Exponential_smoothing... 使用熊猫?
Is there a pandas function to compute a WMA?
是否有 Pandas 函数来计算 WMA?
采纳答案by Wes McKinney
No, there is no implementation of that exact algorithm. Created a GitHub issue about it here:
不,没有那个精确算法的实现。在此处创建了一个关于它的 GitHub 问题:
https://github.com/pydata/pandas/issues/886
https://github.com/pydata/pandas/issues/886
I'd be happy to take a pull request for this-- implementation should be straightforward Cython coding and can be integrated into pandas.stats.moments
我很乐意为此接受拉取请求——实现应该是简单的 Cython 编码并且可以集成到 pandas.stats.moments
回答by Sander van den Oord
Using pandas you can calculate a weighted moving average (wma) using:
.rolling()combined with .apply()
Here's an example with 3 weights and window=3:
使用熊猫,您可以使用以下方法计算加权移动平均线 (wma):
.rolling()结合.apply()
下面是一个具有 3 个权重和 window=3的示例:
data = {'colA': random.randint(1, 6, 10)}
df = pd.DataFrame(data)
weights = np.array([0.5, 0.25, 0.25])
sum_weights = np.sum(weights)
df['weighted_ma'] = (df['colA']
.rolling(window=3, center=True)
.apply(lambda x: np.sum(weights*x) / sum_weights, raw=False)
)
Please notethat in .rolling()I have used argument center=True.
You should check if this applies with your usecase or whether you need center=False.
请注意,在.rolling()我使用了参数center=True。
您应该检查这是否适用于您的用例或您是否需要center=False.

