0
0
NumPydata~5 mins

Covariance with np.cov() in NumPy

Choose your learning style9 modes available
Introduction

Covariance shows how two things change together. It helps us understand if one thing goes up when the other goes up or down.

To find if height and weight of people increase together.
To check if sales of two products move in the same direction.
To understand the relationship between temperature and ice cream sales.
To analyze if two stocks tend to rise or fall together.
To explore how study time and exam scores relate.
Syntax
NumPy
np.cov(x, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)

x is your data array. If y is given, covariance is between x and y.

rowvar=True means each row is a variable, each column is an observation.

Examples
Calculate covariance between two lists x and y.
NumPy
import numpy as np
x = [1, 2, 3]
y = [4, 5, 6]
cov_matrix = np.cov(x, y)
Calculate covariance matrix for two variables stored in rows.
NumPy
data = np.array([[1, 2, 3], [4, 5, 6]])
cov_matrix = np.cov(data)
Calculate covariance matrix when variables are in columns.
NumPy
data = np.array([[1, 4], [2, 5], [3, 6]])
cov_matrix = np.cov(data, rowvar=False)
Sample Program

This code calculates the covariance matrix between two variables x and y. The matrix shows how they change together.

NumPy
import numpy as np

# Two lists representing two variables
x = [2, 4, 6, 8]
y = [1, 3, 5, 7]

# Calculate covariance matrix
cov_matrix = np.cov(x, y)

print("Covariance matrix:")
print(cov_matrix)
OutputSuccess
Important Notes

Covariance values can be positive, negative, or zero.

Positive covariance means both variables increase together.

Negative covariance means one variable increases while the other decreases.

Summary

Covariance measures how two variables change together.

np.cov() calculates covariance matrix from data.

Understanding covariance helps find relationships between data.