Pandas:使用滚动 windows 和用户函数

Pandas: using rolling windows with user functions

我有一个数据框,我从中使用旧式滚动语法估算各种类型的 10 年滚动平均值:

`pandas.rolling_mean(df['x'], 10)`, 
`pandas.rolling_median(df['x'], 10)`

`pandas.rolling_apply(df['x'],10, hodgesLehmanMean)`,

其中 hodgesLehman mean 是我编写的函数(见下文)。

def hodgesLehmanMean(x):
    #Computes the Hodges-Lehman mean = median { [x_i + x+j]/2 }. 
    #Robust to 29% outliers, with high (95% efficiency) in the gaussian case

    N = len(x)
    return 0.5 * numpy.median(x[i] + x[j] for i in range(N) for j in range(i+1,N))
`

既然旧的滚动函数已被弃用,我正在尝试以新的 series.rolling() 样式重写我的代码,即:

`df['x'].rolling(window=10).mean()`, 
`df['x'].rolling(window=10).median()`
 and 
`df['x'].rolling(window=10).hodgesLehmanMean()`.

前两个(平均数和中位数)非常有用。第三个 (hodgesLehmanMean) 不起作用 - 它引发了 AttributeError: 'Rolling' object has no attribute 'hodgesLehmanMean

如何让我的函数使用新的 series.rolling 语法?

您可以拨打Rolling.apply/agg:

df['x'].rolling(window=10).agg(hodgesLehmanMean)

此外,请注意,在您的函数中,您希望将 list 传递给 np.median,而不是 generator

def hodgesLehmanMean(x): 
    return 0.5 * np.median([x[i] + x[j] 
                           for i in range(len(x)) 
                           for j in range(i+1,len(x))])

要更快地实现 hodgesLehmanMean,请查看 unutbu's answer to one of your older questions here