Introduction
Autocorrelation analysis helps us find patterns in data by checking if values repeat over time or space.
Jump into concepts and practice - no test required
import numpy as np def autocorrelation(x, lag=1): n = len(x) x_mean = np.mean(x) numerator = np.sum((x[:n-lag] - x_mean) * (x[lag:] - x_mean)) denominator = np.sum((x - x_mean) ** 2) if denominator == 0: return float('nan') return numerator / denominator
autocorrelation([1, 2, 3, 4, 5], lag=1)
autocorrelation([1, 2, 3, 4, 5], lag=2)
autocorrelation([5, 5, 5, 5, 5], lag=1)
import numpy as np def autocorrelation(x, lag=1): n = len(x) x_mean = np.mean(x) numerator = np.sum((x[:n-lag] - x_mean) * (x[lag:] - x_mean)) denominator = np.sum((x - x_mean) ** 2) if denominator == 0: return float('nan') return numerator / denominator # Example data: daily sales over 7 days sales = np.array([10, 12, 13, 12, 11, 13, 14]) # Calculate autocorrelation for lag 1 and lag 2 ac_lag1 = autocorrelation(sales, lag=1) ac_lag2 = autocorrelation(sales, lag=2) print(f"Autocorrelation at lag 1: {ac_lag1:.3f}") print(f"Autocorrelation at lag 2: {ac_lag2:.3f}")
data?data = [2, 4, 6, 8, 10], what is the autocorrelation at lag 1 using numpy's correlation coefficient?import numpy as np data = [1, 3, 5, 7, 9] result = np.corrcoef(data[:-2], data[2:])[0,2]