Write a program in Python to compute autocorrelation between series and number of lags

PythonPandasServer Side ProgrammingProgramming

Assume, you have series and the result for autocorrelation with lag 2 is,

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

Solution

To solve this, we will follow the steps given below −

  • Define a series

  • Find the series autocorrelation using the below method,

series.autocorr()
  • Calculate the autocorrelation with lag=2 as follows,

series.autocorr(lag=2)

Example

Let’s see the below code to get a better understanding,

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

Output

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
raja
Published on 11-Feb-2021 11:03:06
Advertisements