w3resource

Python Pandas: Compute the autocorrelations of a given numeric series

 

Python Pandas: Data Series Exercise-34 with Solution

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]

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Membership Testing in a Collection

>>> a = ('one', 'two', 'three', 'four', 'five')
>>> if 'one' in a:
...     print('The tuple contains one.')
... 
The tuple contains one.
>>> b = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> if 2 in b.keys():
...     print('The dict has the key of 2.')
... 
The dict has the key of 2.