Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.var() function

Pandas Series.var() function

Pandas Common Functions Common Pandas functions


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


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

]

)

print

(

"Group A data (more concentrated):"

)

print

(

group_a

)

print

(

f

"Mean: {group_a.mean():.2f}"

)

print

(

f

"Variance: {group_a.var():.2f}"

)

print

(

f

"Standard Deviation: {group_a.std():.2f}"

)

print

(

)

print

(

"Group B data (more dispersed):"

)

print

(

group_b

)

print

(

f

"Mean: {group_b.mean():.2f}"

)

print

(

f

"Variance: {group_b.var():.2f}"

)

print

(

f

"Standard Deviation: {group_b.std():.2f}"

)

print

(

)

print

(

"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:

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

]

)

print

(

"Data:"

)

print

(

data

)

print

(

)

Default ddof=1, using the sample variance (dividing by n-1)

sample_var

=

data.

var

(

ddof

=

1

)

print

(

f

"Sample variance (ddof=1): {sample_var:.4f}"

)

ddof=0, using the population variance (dividing by n)

population_var

=

data.

var

(

ddof

=

0

)

print

(

f

"Population variance (ddof=0): {population_var:.4f}"

)

print

(

)

Verification: the square root of the sample variance is approximately equal to the sample standard deviation

import

math

print

(

f

"Square root of the sample variance: {math.sqrt(sample_var):.4f}"

)

print

(

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

]

)

print

(

"Data containing missing values:"

)

print

(

data_with_nan

)

print

(

)

Default skipna=True

var_skipna

=

data_with_nan.

var

(

)

print

(

f

"Variance with skipna=True (default): {var_skipna:.4f}"

)

Set skipna=False

var_no_skipna

=

data_with_nan.

var

(

skipna

=

False

)

print

(

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

]

)

print

(

"Portfolio A (monthly return %):"

)

print

(

portfolio_a

)

print

(

f

"Variance: {portfolio_a.var():.4f}"

)

print

(

f

"Standard deviation (volatility): {portfolio_a.std():.2f}%"

)

print

(

)

print

(

"Portfolio B (monthly return %):"

)

print

(

portfolio_b

)

print

(

f

"Variance: {portfolio_b.var():.4f}"

)

print

(

f

"Standard deviation (volatility): {portfolio_b.std():.2f}%"

)

print

(

)

print

(

"Analysis:"

)

print

(

"- Portfolio A has smaller variance and standard deviation, performing more stably"

)

print

(

"- Portfolio B has larger variance and standard deviation, carrying higher risk"

)

print

(

"- 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


Summary

Series.var() is a fundamental function in statistical analysis. Its main features include:

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.

Pandas Common Functions Common Pandas functions