Calculating Moments with Python
Expected Value
items = [1,2,3,4,5]
average = sum(items)/len(items)
Covariance
import numpy as np
# Sample data
x = [10, 20, 30, 40, 50]
y = [12, 24, 33, 45, 55]
# Calculate covariance matrix
# By default, it calculates sample covariance (divided by N - 1)
matrix = np.cov(x, y)
# Extract the covariance between x and y
covariance = matrix[0, 1]
print("Covariance Matrix:\n", matrix)
print(f"Covariance: {covariance}")
import pandas as pd
# Sample DataFrame
data = {
'X': [10, 20, 30, 40, 50],
'Y': [12, 24, 33, 45, 55]
}
df = pd.DataFrame(data)
# Method A: Pairwise covariance matrix across all columns
matrix = df.cov()
# Method B: Covariance between two specific series directly
covariance = df['X'].cov(df['Y'])
print("Pandas Matrix:\n", matrix)
print(f"Pandas Covariance: {covariance}")