# NumPy Variance

Contents

## 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

## 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)``````
Run Code Copy

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)``````
Run Code Copy

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.

Code copied to clipboard successfully 👍