Pandas: Calculate Covariance with cov()

Compute pairwise covariance of columns in a DataFrame or between Series using the Pandas cov() method. Evaluate joint variability, measure directional relationships across financial asset returns, and configure sample size thresholds.

Introduction to cov() 🔝

The cov() method calculates sample covariance between numerical columns, excluding missing values by default. Unlike correlation, covariance retains the scale of the original variables, where positive values indicate variables move together and negative values indicate opposite movement.

Create numerical sample DataFrame 🔝

We start with a multi-column numerical DataFrame representing asset prices and trading volume.
import pandas as pd

df = pd.DataFrame({
    "ASSET_A": [10, 20, 30, 40, 50],
    "ASSET_B": [12, 24, 33, 45, 57],
    "VOLUME": [100, 150, 130, 180, 200]
})
print(df)
assert df.shape == (5, 3)

Expected output

   ASSET_A  ASSET_B  VOLUME
0       10       12     100
1       20       24     150
2       30       33     130
3       40       45     180
4       50       57     200

Basic covariance matrix 🔝

Call cov() on the DataFrame to calculate the pairwise covariance matrix across numerical columns.
cov_matrix = df.cov()
print(cov_matrix)
assert cov_matrix.loc["ASSET_A", "ASSET_B"] == 277.5

Expected output

         ASSET_A  ASSET_B  VOLUME
ASSET_A    250.0    277.5   550.0
ASSET_B    277.5    310.5   605.0
VOLUME     550.0    605.0  1470.0

Covariance between two Series 🔝

Invoke cov() directly on a Series, passing another Series as the argument to evaluate their pairwise covariance scalar value.
s_cov = df["ASSET_A"].cov(df["ASSET_B"])
print(f"Covariance: {s_cov}")
assert s_cov == 277.5

Expected output

Covariance: 277.5

Exercise: compute asset returns covariance 🔝

Given two Series ret_x = pd.Series([1, 2, 3, 4, 5]) and ret_y = pd.Series([5, 4, 3, 2, 1]), compute their covariance and verify that the resulting value equals -2.5.

Exercise solution 🔝

Solution creating the Series and calculating cov().
ret_x = pd.Series([1, 2, 3, 4, 5])
ret_y = pd.Series([5, 4, 3, 2, 1])
answer = ret_x.cov(ret_y)
print(answer)
assert answer == -2.5

Expected output

-2.5

Practice in Google Colab 🔝

Interactive Colab Notebook

Practice cov() examples interactively directly in your browser:

Open In Colab View on GitHub

Reference: Pandas cov() documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer