w3resource

Pandas Data Series: Compute the autocorrelations of a given numeric series

 


Write a Pandas program to compute the autocorrelations of a given numeric series.

From Wikipedia:
Autocorrelation, also known as serial correlation, is the correlation of a signal with a delayed copy of itself as a function of delay. Informally, it is the similarity between observations as a function of the time lag between them.

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
num_series = pd.Series(np.arange(15) + np.random.normal(1, 10, 15))
print("Original series:")
print(num_series)
autocorrelations = [num_series.autocorr(i).round(2) for i in range(11)]
print("\nAutocorrelations of the said series:")
print(autocorrelations[1:])

Sample Output:

Original series:
0     13.207262
1      4.098685
2     -1.435534
3     13.626760
4     -1.435962
5     28.823612
6     -3.299048
7     14.048354
8      6.991233
9     13.289209
10    23.032654
11     7.080452
12    -2.453857
13    -2.346193
14    17.873884
dtype: float64

Autocorrelations of the said series:
[-0.38, 0.1, -0.43, 0.03, 0.35, -0.2, 0.04, -0.59, 0.34, 0.11]

Explanation:

num_series = pd.Series(np.arange(15) + np.random.normal(1, 10, 15)): This line creates a Pandas Series object 'num_series' containing 15 elements, where each element is the sum of a corresponding element in a range of 15 numbers and a random number drawn from a normal distribution with a mean of 1 and standard deviation of 10.

autocorrelations = [num_series.autocorr(i).round(2) for i in range(11)]: This code computes the autocorrelations of the 'num_series' series up to a lag of 10, using the autocorr() function of the series. The resulting autocorrelations are stored in the 'autocorrelations' list, with each element rounded to 2 decimal places. print(autocorrelations[1:]): Finally, the code prints the autocorrelations from the first lag to the 10th lag using list slicing ([1:]).

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to replace missing white spaces in a given string with the least frequent character.
Next: Write a Pandas program to create a TimeSeries to display all the Sundays of given year.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.