Computing the Sample Variance of a distribution using Python

The Python function variance() from the statistics module takes an iterable providing the sample data as parameter and returns the sample variance. Variance is the expected value of the squared distances from the mean of a distribution.

Statistics Updated 13 Jan 2017 2 min read

Function Signature

variance(sampleValues, mean=None)

Parameters

sampleValues – The sample value. The outcomes of a random variable. The distribution for which the variance is to be computed. The parameter is any Python sequence or an iterable.

mean – The arithmetic mean of the sample. The default value is None. When the mean is not provided the function automatically calculates the Mean and uses it while calculating the variance.

Overview

  • The variance is given by the mean squared distance of the values from the mean of the distribution.
  • It is a measure of dispersion. Variance describes how the values in a distribution is scattered or concentrated around the mean.
  • Variance is the second moment of a distribution.
  • The function variance() from the statistics module returns the sample variance.
  • The Sample Variance s2 is given by the formula

s2 = i(1 to n)∑(xi-x̄)2/n-1

  • Using (n-1) in the denominator of the variance calculation makes the Sample Variance an unbiased estimator of the Population Variance.

Exceptions

Python raises a StatisticsError if the data passed inside the variance() function is empty.

Computing variance of a distribution

The entries of the first column correspond to values of a distribution. The values are added and divided by the count of the distribution to get the mean value. The entries of the second column correspond to the squared distances from the mean. At the end of the second column squared distances from the mean are summed up and divided by the number of values in the distribution -1. This gives the sample variance.

Sample Value(X)Squared Distance From the mean(X-E(X))2
554.4567901234568
561.23456790123458
549.67901234567903
5316.9012345679013
5226.1234567901235
6797.7901234567901
561.23456790123458
6223.9012345679012
593.56790123456789
Mean = SUM(x)/COUNT(x) = 57.11Variance = (X-E(X))2/Count(X)-1 = 23.11

Example

python
# import the statistics module

import statistics

sampleData = [55,56,54,53,52,67,56,62,59]

sampleVariance = statistics.variance(sampleData)

print("Sample variance of the distribution is %.2f"%(sampleVariance))

Output

Output
Sample variance of the distribution is 23.11