Login
📚 Python for Introductory Statistics
Chapters ▾

6.2 The Variance

Watch demo video

How spread out are the data values from the "center"? The most common measures of variation, or spread, of data are the standard deviation and variance.

The variance of a data set is the average of the squared deviations(distances) of the data values from the mean.

  1. The sample variance of the data set x1,x2,x3,...,xn is given by s2=Σ(xiμ)2n1
  2. The population variance of the data set x1,x2,x3,...,xN is given by σ2=Σ(xiμ)2N

numpy syntax for sample variance:

import numpy as np
x = [x1,x2,x3,...]
np.var(x,ddof=1)    is (n-ddof)

numpy syntax for population variance:

import numpy as np
x = [x1,x2,x3,...]
np.var(x)     

Note: ddof degrees of freedom for numerator is 1 for sample and 0 for population variance. ddof=0 by default in numpy.

Example: find the sample variance of the dataset 1,2,3,4,5

  1. Click + Code
  2. Type import numpy as np
  3. TYpe x = [1,2,3,4,5]
  4. Type np.var(x,ddof=1)
  5. Click play button
import numpy as np
x = [1,2,3,4,5]
np.var(x,ddof=1)
Show expected output
2.5

Interpretation: The sample variance is 2.5

Example: find the population variance of the data set 1,2,3,4,5

import numpy as np
x = [1,2,3,4,5]
np.var(x)      #in numpy ddof=0 by default
Show expected output
2.0

Interpretation: The population variance is 2.0

Example: The salaries for the eight Board of Ethics workers for the City of Chicago are listed below. Write a numpy program to calculate the population variance.

139740, 100716, 80844, 124056, 79812, 87564, 96096, 96096

import numpy as np
x = [139740, 100716, 80844, 124056, 79812, 87564, 96096, 96096]

np.var(x,ddof=0)
Show expected output
389385609.75

Interpretation: The population variance for the given salaries is 389385609.75

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.