Compute unbiased sample variance for values across Series or DataFrames using the Pandas var() method. Measure data dispersion, configure delta degrees of freedom (ddof), and handle missing observations effectively.
var() method calculates sample variance for requested numerical columns. By default, Pandas uses sample variance with $ ext{ddof}=1$ (delta degrees of freedom) and excludes missing values (skipna=True).import pandas as pd
df = pd.DataFrame({
"COL_X": [2, 4, 6, 8, 10],
"COL_Y": [5, 10, 15, 20, 25]
})
print(df)
assert df.shape == (5, 2)
Expected output
COL_X COL_Y
0 2 5
1 4 10
2 6 15
3 8 20
4 10 25
var() on the DataFrame to compute the sample variance across numerical columns.var_res = df.var()
print(var_res)
assert var_res["COL_X"] == 10.0
Expected output
COL_X 10.0
COL_Y 62.5
dtype: float64
var() directly to a single column or standalone Pandas Series.s_var = df["COL_X"].var()
print(f"Variance: {s_var}")
assert s_var == 10.0
Expected output
Variance: 10.0
vals = pd.Series([1, 3, 5, 7, 9], name="VALS"), compute its sample variance using var() and verify that it equals 10.0.var().vals = pd.Series([1, 3, 5, 7, 9], name="VALS")
answer = vals.var()
print(answer)
assert answer == 10.0
Expected output
10.0
Practice var() examples interactively directly in your browser:
Reference: Pandas var() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.