Pandas Series.var() function
Series.var() is a function in Pandas used to compute the variance of a Series. Variance is the square of the standard deviation; it measures the dispersion of data and is a fundamental metric in statistical analysis.
A larger variance means the data is more dispersed; a smaller variance means it is more concentrated. It is widely used in statistical analysis, machine learning, signal processing, and other fields.
Basic syntax and parameters
var() is a member function of the Series object and is called directly with the dot operator.
Syntax format
Series.var(axis=None, skipna=True, level=None, numeric_only=None, ddof=1, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| axis | int | Specifies the axis; a Series has only one axis, so this parameter exists mainly for compatibility with DataFrame. | None |
| skipna | bool | If True, NaN values are skipped during the calculation; if False, encountering NaN results in NaN. | True |
| level | int or str | If the Series has a MultiIndex, specifies the level to calculate. | None |
| numeric_only | bool | If True, only numeric data is calculated; otherwise, conversion to numeric is attempted. | False |
| ddof | int | The degrees-of-freedom adjustment parameter. ddof=1 uses the sample variance (n-1); ddof=0 uses the population variance (n). | 1 |
Return Value
- Return Type:
float - Description: Returns the variance of the elements in the Series. By default, the sample variance is used (dividing by n-1).
Example
Let us thoroughly master Series.var() through a series of examples from simple to complex.
Example 1: Basic Usage - Understanding the Concept of Variance
Variance is the square of the standard deviation, measuring the degree of deviation of data from the mean.
Example
import
pandas
as
pd
Two sets of data
group_a
=
pd.
Series
(
[
85
,
86
,
87
,
88
,
89
]
)
group_b
=
pd.
Series
(
[
70
,
75
,
85
,
95
,
100
]
)
(
"Group A data (more concentrated):"
)
(
group_a
)
(
f
"Mean: {group_a.mean():.2f}"
)
(
f
"Variance: {group_a.var():.2f}"
)
(
f
"Standard Deviation: {group_a.std():.2f}"
)
(
)
(
"Group B data (more dispersed):"
)
(
group_b
)
(
f
"Mean: {group_b.mean():.2f}"
)
(
f
"Variance: {group_b.var():.2f}"
)
(
f
"Standard Deviation: {group_b.std():.2f}"
)
(
)
(
"Note: variance is the square of the standard deviation (2.50^2 = 6.25, 12.50^2 = 156.25)"
)
Running result:
A组数据(较集中):
0 85
1 86
2 87
3 88
4 89
dtype: int64
平均值:85.00
方差:2.50
标准差:1.58
B组数据(较分散):
0 70
1 75
2 85
3 95
4 100
dtype: int64
平均值:85.00
方差:156.25
标准差:12.50
注意:方差是标准差的平方 (1.58^2 ≈ 2.50, 12.50^2 = 156.25)
Code analysis:
- Group A has a variance of 2.50, with very concentrated data.
- Group B has a variance of 156.25, with very dispersed data.
- Variance = standard deviation squared (the approximation is due to the ddof=1 adjustment).
Example 2: The Role of the ddof Parameter
ddof The parameter controls whether to use the sample variance or the population variance.
Example
import
pandas
as
pd
Create a dataset
data
=
pd.
Series
(
[
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
]
)
(
"Data:"
)
(
data
)
(
)
Default ddof=1, using the sample variance (dividing by n-1)
sample_var
=
data.
var
(
ddof
=
1
)
(
f
"Sample variance (ddof=1): {sample_var:.4f}"
)
ddof=0, using the population variance (dividing by n)
population_var
=
data.
var
(
ddof
=
0
)
(
f
"Population variance (ddof=0): {population_var:.4f}"
)
(
)
Verification: the square root of the sample variance is approximately equal to the sample standard deviation
import
math
(
f
"Square root of the sample variance: {math.sqrt(sample_var):.4f}"
)
(
f
"Sample standard deviation: {data.std():.4f}"
)
Running result:
数据:
0 2
1 4
2 4
3 4
4 5
5 5
6 7
7 9
dtype: int64
样本方差(ddof=1):5.1429
总体方差(ddof=0):4.5000
样本方差的平方根:2.2678
样本标准差:2.2678
Example 3: Handling Data with Missing Values
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series containing missing values
data_with_nan
=
pd.
Series
(
[
10
,
20
,
np.
nan
,
30
,
40
,
np.
nan
,
50
]
)
(
"Data containing missing values:"
)
(
data_with_nan
)
(
)
Default skipna=True
var_skipna
=
data_with_nan.
var
(
)
(
f
"Variance with skipna=True (default): {var_skipna:.4f}"
)
Set skipna=False
var_no_skipna
=
data_with_nan.
var
(
skipna
=
False
)
(
f
"Variance with skipna=False: {var_no_skipna}"
)
Running result:
Data containing missing values:
0 10.0
1 20.0
2 NaN
3 30.0
4 40.0
5 NaN
6 50.0
dtype: float64
skipna=True(默认)时的方差:250.0000
skipna=False 时的方差:nan
Example 4: Practical Application Comparison of Variance and Standard Deviation
In practical applications, variance and standard deviation each have their advantages.
Example
import
pandas
as
pd
Simulate monthly returns (%) for two investment portfolios
portfolio_a
=
pd.
Series
(
[
2.5
,
3.0
,
1.0
,
1.5
,
2.0
,
2.8
,
0.5
,
1.2
,
1.8
,
2.2
]
)
portfolio_b
=
pd.
Series
(
[
5.0
,
3.5
,
8.0
,
2.0
,
6.5
,
4.0
,
7.0
,
1.5
,
4.5
,
2.0
]
)
(
"Portfolio A (monthly return %):"
)
(
portfolio_a
)
(
f
"Variance: {portfolio_a.var():.4f}"
)
(
f
"Standard deviation (volatility): {portfolio_a.std():.2f}%"
)
(
)
(
"Portfolio B (monthly return %):"
)
(
portfolio_b
)
(
f
"Variance: {portfolio_b.var():.4f}"
)
(
f
"Standard deviation (volatility): {portfolio_b.std():.2f}%"
)
(
)
(
"Analysis:"
)
(
"- Portfolio A has smaller variance and standard deviation, performing more stably"
)
(
"- Portfolio B has larger variance and standard deviation, carrying higher risk"
)
(
"- From a risk perspective, Portfolio A is more suitable for conservative investors"
)
Running result:
投资组合 A(月度收益 %):
0 2.5
1 3.0
2 1.0
3 1.5
4 2.0
5 2.8
6 0.5
7 1.2
8 1.8
9 2.2
dtype: int64
方差:1.29
标准差(波动率):1.14%
投资组合 B(月度收益 %):
0 5.0
1 -3.5
2 8.0
3 -2.0
4 6.5
5 -4.0
6 7.0
7 -1.5
8 4.5
9 -2.0
dtype: int64
方差:19.56
标准差(波动率):4.42%
分析:组合 B 的风险(波动率)约是组合 A 的 4 倍。
Notes
- Variance is the square of the standard deviation; their relationship is: std = sqrt(var).
- The sample variance (ddof=1) is used by default, suitable for statistical analysis.
- The unit of variance is the square of the original data's unit, which is not intuitive; the standard deviation retains the original unit and is easier to interpret.
- In scenarios requiring variance for mathematical computations (such as covariance analysis), variance should be used.
Summary
Series.var() is a fundamental function in statistical analysis. Its main features include:
- Uses the sample variance by default (ddof=1).
- Variance is the square of the standard deviation, making it more convenient in mathematical operations.
- The standard deviation retains the original unit, making it easier to understand intuitively.
- In finance, both variance and standard deviation are used to measure risk (volatility).
In practical applications, if you need an intuitive understanding of data dispersion, the standard deviation is more appropriate; if you need mathematical operations (such as computing covariance), variance is more convenient.
Common Pandas functions