Get Variance of NumPy Array in Python – np.var() Function (3 Examples)

This article shows how to apply the np.var function in the Python programming language.

Preparing the Examples

import numpy                         # Import numpy
x = np.array([[8, 2, 1, 7, 7, 5],    # Constructing a NumPy array in Python
              [4, 10, 5, 9, 1, 4]])
print(x)
# [[ 8  2  1  7  7  5]
#  [ 4 10  5  9  1  4]]

Example 1: Calculate Variance of All Array Values in Python

print(np.var(x))                     # Computing the variance of all values
# 8.354166666666666

Example 2: Calculate Variance by Array Rows in Python

print(np.var(x, axis = 1))           # Computing the variance by rows
# [7.         9.58333333]

Example 3: Calculate Variance by Array Columns in Python

print(np.var(x, axis = 0))           # Computing the variance by columns
# [ 4.   16.    4.    1.    9.    0.25]

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top