Pandas DataFrame cov() method with examples

Spread the love

The cov() method in pandas computes the pairwise covariance of columns, excluding NA/null values. The returned data frame is the covariance matrix of the columns of the DataFrame. Both NA and null values are automatically excluded from the calculation.

Example –

Let’s read a dataset to work with.

import pandas as pd
from sklearn import datasets
housing = datasets.fetch_california_housing()
df = pd.DataFrame(, columns=housing.feature_names)

Now to create a covariance matrix in pandas, we can use the df.cov() method.

cov_matrix = df.cov()

Rating: 1 out of 5.

Leave a Reply