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
)。
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 requiredmean : boolean, default True
If True computes weighted mean, else weighted sum
关于python - 如何使用 pandas 中的自定义权重计算滚动平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32368078/