python - 如何使用 pandas 中的自定义权重计算滚动平均值?

标签 python pandas moving-average

Pandas 文档 http://pandas.pydata.org/pandas-docs/stable/computation.html有一个如何计算移动平均线的示例:

ser = pd.Series(np.random.randn(10), index=pd.date_range('1/1/2000', periods=10))
pd.rolling_window(ser, 5, 'boxcar')

第二行计算滚动平均值,窗口为 5,并且五个观测值的权重相等。文档引人入胜地提到了使用自定义权重的可能性(“当传递 win_type 而不是显式指定权重时......”),但是如何做到这一点?

谢谢!

最佳答案

我不是数学专家,但坚定解释你需要什么here

我尝试测试一下:

import pandas as pd

ser = pd.Series([1,1,1], index=pd.date_range('1/1/2000', periods=3))
print ser

rm1 = pd.rolling_window(ser, window=[2,2,2], mean=False)
rm2 = pd.rolling_window(ser, window=[2,2,2]) #, mean=True

print rm1
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     6
#Freq: D, dtype: float64
print rm2
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     1
#Freq: D, dtype: float64

我将 window 设置为 ndarray ([2,2,2]) 并计算加权和 (rm1) >) 和加权平均值 (rm2)。

pandas.rolling_window :

window : int or ndarray:
Weighting window specification. If the window is an integer, then it is treated as the window length and win_type is required

mean : boolean, default True
If True computes weighted mean, else weighted sum

关于python - 如何使用 pandas 中的自定义权重计算滚动平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32368078/

相关文章:

python - 最近启动的 Google Compute Engine VM 的非确定性连接成功

python - 从不同长度的子子列表中查找全局最小值

Python Itertools Combinatinos 检索空列表

python - 将数据框列值转换为列表

python - 计算移动平均线

python - SWIG 使 Python 崩溃

python - Pandas:垃圾收集丢弃的列以释放内存

python - 按 ID 分组,选择同一 ID 列中的最高值

r - 计算移动平均线