How to compute the covariance matrix of two Pandas DataFrame columns using Python
• 1 minThe covariance is a widely used statistical estimate to measure how much a variable does vary when the other increase or decreases.
Here is an example of when you plot two variables.
![](https://blog.thepythonyouneed.com/content/images/2022/04/image-2.png)
The covariance is also used to compute the correlation between two variables.
The Pandas library provides the DataFrame.cov() method that will compute the covariance for you.
Here is the code
![](https://blog.thepythonyouneed.com/content/images/2022/04/image-3.png)
# to work with dataframe
import pandas as pd
# We create our sample dataset with negative covariance
df = pd.DataFrame({"col1": range(10),
"col2": range(10)[::-1]})
# We plot to check the coviariance visually
df.plot(kind="scatter", x="col1", y="col2")
# We compute and print the covariance between the two variables
print(df[["col1", "col2"]].cov())
Here you are! You should be by now the king of covariance in Python!