How to compute the covariance matrix of two Pandas DataFrame columns using Python

1 min readPandasDataFrameStatisticsData
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

The 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.

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

# 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())
How to compute the covariance

Here you are! You should be by now the king of covariance in Python!

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.