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

How do I calculate a rolling mean with custom weights in pandas?

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')

第二行计算滚动平均值,window 为 5,并且五个观察值中的每一个的权重相等。文档诱人地提到了使用自定义权重的可能性 ("When passing a win_type instead of explicitly specifying the weights..."),但是你是怎么做到的?

谢谢!

我不是数学专家,但 stahlous 解释你需要什么 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

首先在新的 pandas 版本中 rolling 语法已经改变 如果你只需要三角形window,你可以这样做:

ser.rolling(5, win_type='triang').mean()

其他一些标准windowsare also supported

如果你真的想要自定义(自制)平均权重,你可以像这样使用自定义 .apply 和加权平均 np.average

import numpy as np

# your code here

weights = [1, 2, 8, 3, 2]  # something unusual
ser.rolling(5).apply(lambda seq: np.average(seq, weights=weights))