 # Python | numpy.cov () function

Covariance provides a measure of the strength of the correlation between two or more variables. An element of the covariance matrix C ij is the covariance of xi and xj. The element Cii is the variance of xi.

• If COV (xi, xj) = 0, then the variables are uncorrelated
• If COV (xi, xj) & gt; 0, then the variables are positively correlated
• If COV (xi, xj) & gt; & lt; 0, variables are negatively correlated

Syntax: numpy.cov (m, y = None, rowvar = True, bias = False, ddof = None, fweights = None, aweights = None)

Parametrs:
m: [array_like] A 1D or 2D variables. variables are columns
y: [array_like] It has the same form as that of m.
rowvar: [bool, optional] If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed:
bias: Default normalization is False. If bias is True it normalize the data points.
ddof: If not None the default value implied by bias is overridden. Note that ddof = 1 will return the unbiased estimate, even if both fweights and aweights are specified.
fweights: fweight is 1-D array of integer frequency weights
aweights: aweight is 1-D array of observation vector weights.

Returns: It returns ndarray covariance matrix

Example # 1:

 ` # Python code for demonstration ` ` # using numpy.cov ` ` import ` ` numpy as np `   ` x ` ` = ` ` np.array ([[` ` 0 ` `, ` ` 3 ` `, ` ` 4 ` `], [` ` 1 ` `, ` ` 2 ` `, ` ` 4 ` `], [` ` 3 ` `, ` ` 4 ` `, ` ` 5 ` `]]) ` ` `  ` print ` ` (` ` "Shape of array:" ` `, np.shape (x)) ` ` `  ` print ` ` (` ` "Covarinace matrix of x:" ` `, np.cov (x )) `

Exit:

` Shape of array: (3, 3) Covarinace matrix of x: [[4.33333333 2.83333333 2.] [2.83333333 2.33333333 1.5] [2. 1.5 1.]] `

Example No. 2:

 ` # Python code for demonstration ` ` # using numpy. cov ` ` import ` ` numpy as np `   ` x ` ` = ` ` [` ` 1.23 ` `, ` ` 2.12 ` `, ` ` 3.34 ` `, ` ` 4.5 ` `] `   ` y ` ` = ` ` [` ` 2.56 ` `, ` ` 2.89 ` `, ` ` 3.76 ` , ` 3.95 ` `] ` ` `  ` # find out covariance relative to columns ` ` cov_mat ` ` = ` ` np.stack ((x, y), axis ` ` = ` ` 0 ` `) `   ` print ` ` (np.cov (cov_mat)) `

Exit:

` [[2.03629167 0.9313] [0.9313 0.4498]] `

Example # 3 :

 ` # Python code for demonstration ` ` # using numpy.cov ` ` import ` ` nump y as np `   ` x ` ` = ` ` [` ` 1.23 ` `, ` ` 2.12 ` `, ` ` 3.34 ` `, 4.5 ] ````   y = [ 2.56 , 2.89 , 3.76 , 3.95 ]   # find out row covariance cov_mat = np.stack ((x, y), axis = 1 )    print ( "shape of matrix x and y:" , np.shape (cov_mat))   print ( " shape of covariance matrix: " , np.shape (np.cov (cov_mat)))    print (np.cov (cov_mat)) ```

Exit:

` shape of matrix x and y: (4 , 2) shape of covariance matrix: (4, 4) [[0.88445 0.51205 0.2793 -0.36575] [0.51205 0.29645 0.1617 -0.21175] [0.2793 0.1617 0.0882 -0.1155] [-0.36575 -0.21175 -0.1155 0.15125]] `