NumPy var: How to calculate variance in Python

You can calculate the variance of a NumPy array, list, and tuple in Python.

import numpy

a1 = numpy.array([1, 2, 3])
a2 = [1, 2, 3]
a3 = (1, 2, 3)

s1 = numpy.var(a1)
s2 = numpy.var(a2)
s3 = numpy.var(a3)

print(s1)  # 0.6666666666666666
print(s2)  # 0.6666666666666666
print(s3)  # 0.6666666666666666

Axis

If the argument is a multi-dimension array like a matrix or tensor, you can use axis argument.

import numpy

a = numpy.array([[1, 2, 3], [4, -7, 10]])

v = numpy.var(a, axis=1)

print(v)  # [ 0.66666667 49.55555556]
print(type(v))  # <class 'numpy.ndarray'>

axis=1 means numpy.var computes [1, 2, 3] and [4, -7, 10] so returns numpy.ndarray. The first 0.66666667 is the variance of [1, 2, 3] and the second 49.55555556 is the variance of [4, -7, 10].

The following is in tha case the axis is 0.

import numpy

a = numpy.array([[1, 2, 3], [4, -7, 10]])

v = numpy.var(a, axis=0)

print(v)  # [ 2.25 20.25 12.25]
print(type(v))  # <class 'numpy.ndarray'>
  • (1, 4) -> 2.25
  • (2, -7) -> 20.25
  • (3, 10) -> 12.25

NumPy Statistics

NumPy Tutorial