用 Python 编写一个程序,以计算时间序列和滞后数之间的自相关性
假设,您有一个序列,滞后 2 的自相关性结果为,
Series is: 0 2.0 1 10.0 2 3.0 3 4.0 4 9.0 5 10.0 6 2.0 7 NaN 8 3.0 dtype: float64 series correlation: -0.4711538461538461 series correlation with lags: -0.2933396642805515
解决方案
为了解决这个问题,我们将按照以下步骤进行 −
定义一个序列
使用以下方法查找序列自相关性,
series.autocorr()
按如下方式计算滞后 = 2 的自相关性,
series.autocorr(lag=2)
示例
让我们看下面的代码来更好地理解,
import pandas as pd import numpy as np series = pd.Series([2, 10, 3, 4, 9, 10, 2, np.nan, 3]) print("Series is:\n", series) print("series correlation:\n",series.autocorr()) print("series correlation with lags:\n",series.autocorr(lag=2))
输出
Series is: 0 2.0 1 10.0 2 3.0 3 4.0 4 9.0 5 10.0 6 2.0 7 NaN 8 3.0 dtype: float64 series correlation: -0.4711538461538461 series correlation with lags: -0.2933396642805515
广告