将自相关计算为 Python 中滞后的函数

Calculate autocorrelation as a function of lag in Python

In python (+ pandas/numpy/scipy/statsmodels) 是否有 return 自相关滞后的函数?是否存在现成的库函数?

为了避免混淆,我想要以下内容,只是我不想绘制它,但我希望它 return 编成一个系列(pd.Series 或 pd.DataFrame):

import numpy as np
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf
from matplotlib import pyplot as plt
plt.ion()
s = pd.Series(np.sin(range(1,100))) + pd.Series(np.random.randn(99))
plot_acf(s)

实际上,我想要 pd.Series.autocorr() returns 但我想要一个序列而不是标量 returned,其中该序列包含各种滞后的自相关。

编辑:

实现上述目标的一种方法是:

pd.Series([s.autocorr(i) for i in range(0,s.shape[0]-1)], index=range(0,s.shape[0]-1))

只能想到自己的加速方法vectorize

np.vectorize(s.autocorr)(np.arange(0,len(s)-1))

Statsmodels acf 函数怎么样?

import statsmodels.api as sm

np.random.seed(1234)
s = pd.Series(np.sin(range(1,100))) + pd.Series(np.random.randn(99))
pd.Series(sm.tsa.acf(s, nlags=5))

产量

0    1.000000
1    0.033136
2   -0.124275
3   -0.396403
4   -0.248519
5    0.078170
dtype: float64