The Python statistics.covariance() function is a measure of the relationship between two random variables. The covariance indicates how two variables are related and also helps to know whether the two variables vary together or differ from each other values.
A positive covariance value determines that different variables movie in same direction. Similarly, if one random variable decreases, the other variable also decreases.
A negative covariance values determines the variables move in opposite direction. Similarly, if one random variable decreases, the other variable increases.
When the two random variables are independent of each other, the covariance between them is zero.
SyntaxFollowing is the basic syntax for the statistics.covariance() function.
statistics.covariance(x, y, /)Parameters
This function contains sequence of elements like list, tuple, iterator or any array with the same length as an input.
Return ValueThis returns the sample covariance of two input points x and y.
Example 1In the below example we are finding covariance for the given values using statistics.covariance() Function.
import statistics a = [1, 2, 3, 4, 5, 6, 7] b = [9, 8, 7, 6, 5, 4, 3] c = statistics.covariance(a, b) print("Sample covariance between a and b:", c)Output
The result is produced as follows −
Sample covariance between a and b: -4.666666666666667Example 2
Now, we are importing statistics in the given code using statistics.covariance() function.
from statistics import covariance a = [3, 4, 5, 6, 7, 8] b = [2, 4, 6, 7, 8, 9] c = covariance(a,b) print(c)Output
This produces the following result −
4.8Example 3
Here, we are calculating the numpy covariance using statistics.covariance() function.
import numpy as np n = [0.34, 4.54, 3.22, 2.12, 0.12] p = [1.23, 3.45, 2.2, 1.2, 0.3] w = np.cov(n,p) print(w)Output
We will get the output as follows −
[[3.55532 2.10384] [2.10384 1.43513]]Example 4
In the below example we are calculating the covariance using statistics.covariance() function.
import statistics s = [2, 3, 4, 5, 6] f = [1, 2, 3, 4, 5] g = statistics.covariance(s, f) print(g)Output
The output obtained is as follows −
2.5
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4