How to calculate sample and population variance in Python?

By Shivang Yadav Last updated : November 22, 2023

Variance in statistics is a measure that shows the amount of dispersion in the dataset.

Sample Variance

Sample variance has a similar formula to that of variance, but the sample variance formula involves dividing by (n-1) instead of n.
Formula:

Sample Variance

Where,

  • Xi is each individual data point in the sample.
  • X is the mean of the sample.
  • n is the number of data points in the sample.

Population Variance

The population variance( σ2) is the average squared deviations from the mean of a set of data points in a population.

Formula:

Population Variance

Where:

  • Xi is each individual data point in the population.
  • σ is the mean of the population.
  • N is the number of data points in the population.

Calculating Sample and Population Variance

To calculate the Sample and Population Variance in Python, use the variance() and pvariance() method of variance package from the statistics library. The variance() returns the sample variance whereas, the pvariance() returns the population variance from the given sample data (or, population).

Example 1: Python program to calculate sample variance

# program to calculate sample variance in python
from statistics import variance

# define data
dataSet = [2, 5, 7, 1, 7, 4, 8, 11, 6, 8, 3, 10]
print("The data in the dataset is", dataSet)

sampleVariance = variance(dataSet)
print("Sample Variance : ", sampleVariance)

Output

The data in the dataset is [2, 5, 7, 1, 7, 4, 8, 11, 6, 8, 3, 10]
Sample Variance :  9.636363636363637

Example 2: Python program to calculate population variance

# program to calculate population variance in python 
from statistics import pvariance

#define data
dataSet = [2, 5, 7, 1, 7, 4, 8, 11, 6, 8, 3, 10]
print("The data in the dataset is", dataSet)

pVariance = pvariance(dataSet)
print("Population Variance : ", pVariance)

Output

The data in the dataset is [2, 5, 7, 1, 7, 4, 8, 11, 6, 8, 3, 10]
Population Variance :  8.833333333333334

Python SciPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.