是的,pandas那部分确实没有很好的文档说明。如果你不使用标准窗口类型,我认为你可能需要使用rolling.apply()。我尝试过并成功了:
>>> import numpy as np
>>> import pandas as pd
>>> d = pd.DataFrame({'a':range(10), 'b':np.random.random(size=10)})
>>> d.b = d.b.round(2)
>>> d
a b
0 0 0.28
1 1 0.70
2 2 0.28
3 3 0.99
4 4 0.72
5 5 0.43
6 6 0.71
7 7 0.75
8 8 0.61
9 9 0.14
>>> wts = np.array([-1, 2])
>>> def f(w):
def g(x):
return (w*x).mean()
return g
>>> d.rolling(window=2).apply(f(wts))
a b
0 NaN NaN
1 1.0 0.560
2 1.5 -0.070
3 2.0 0.850
4 2.5 0.225
5 3.0 0.070
6 3.5 0.495
7 4.0 0.395
8 4.5 0.235
9 5.0 -0.165
我认为这是正确的。关闭的原因在于rolling.apply的签名是rolling.apply(func, *args, **kwargs)
,如果你直接将weights发送到函数中,它们会被解压成元组,除非你将它们作为1-tuple (wts,)
发送,但那很奇怪。
np.average
,它支持提供权重。 - Nickil Maveli