Pandas DataFrame cov() Method – Be on the Right Side of Change (original) (raw)


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import numpy as np


The cov() method computes pair-wise co-variances across the series of a DataFrame. This analysis determines the relationship between various measures across time. Any NaN/NULL values do not count.

The syntax for this method is as follows:

DataFrame.cov(min_periods=None, ddof=1)

Parameters Description
min_periods The minimum number of observations required per pair of columns to have a valid result. This parameter is an integer and is optional.
ddof This parameter is the Delta degrees of freedom. This parameter is the divisor used in calculations (N - ddof), where N represents the number of elements. By default, the value is one (1).

For this example, a random series of numbers generate to see the cov() method in action.

np.random.seed(75) df = pd.DataFrame(np.random.randn(35, 3),columns=['Level-A', 'Level-B', 'Level-C']) result = df.cov(min_periods=12) print(result)

Output

| | Level-A | Level-B | Level-C | | | --------- | -------- | -------- | -------- | | Level-A | 1.133852 | 0.139968 | 0.159209 | | Level-B | 0.139968 | 0.898406 | 0.540002 | | Level-C | 0.159209 | 0.540002 | 1.384775 |


More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.