NumPy Variance - var()


NumPy Variance

In this tutorial, you will learn how to use the numpy.var() function in NumPy to calculate the variance of data given in an array.

Syntax

The syntax of numpy var() function is

numpy.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)

where

ParameterDescription
aThe input array or object whose variance needs to be calculated.
axis[Optional] The axis along which the variance is computed. If None, the variance is computed for the flattened array.
dtype[Optional] The data type used to calculate the variance.
out[Optional] Output array in which to place the result.
ddof[Optional] Delta degrees of freedom. The divisor used in the calculation is N - ddof, where N is the number of elements.
keepdims[Optional] If True, the reduced dimensions are retained in the result.
where[Optional] Elements to include in the variance.

Examples

Let us explore examples of using the numpy.var() function.

1. Calculating Variance of a 1D Array

In this example, we calculate the variance of a simple 1D array.

In the following program, we take a 1D numpy array in data, and find the variance of this array. We shall print the calculated variance to the standard output.

Python Program

import numpy as np

data = np.array([5, 8, 10, 12, 15])
variance = np.var(data)

print("Variance:", variance)

Output

Variance: 10.0

2. Calculating Variance Along Axis

We can also calculate the variance along a specified axis of a 2D array.

In the following program, we take a 2D numpy array in data, and find the variance of this array along axis=0 and axis=1 separately. We shall print the calculated variances to the standard output.

Python Program

import numpy as np

data = np.array([[5, 8, 10],
                 [12, 15, 18]])

variance_along_axis0 = np.var(data, axis=0)
variance_along_axis1 = np.var(data, axis=1)

print("Variance along Axis 0:", variance_along_axis0)
print("Variance along Axis 1:", variance_along_axis1)

Output

Variance along Axis 0: [8.25 8.25 8.25]
Variance along Axis 1: [4.44444444 4.44444444]

Summary

In this NumPy Tutorial, we have seen how to find the variance of a given numpy array using numpy.var() function. We have used this function to calculate variance for both 1D and 2D arrays.