How to Calculate NumPy Variance and Std of a Matrix in Python?

This recipe will help you calculate the NumPy variance and other statistical calculations of a matrix in Python.

Recipe Objective - How to Calculate NumPy Variance and Std of a Matrix in Python? 

NumPy, a powerful numerical computing library in Python, provides essential functions for statistical analysis on arrays and matrices. Check out this recipe to understand how to calculate the variance and standard deviation of a matrix using NumPy. Additionally, we'll create a function named calculate() in a file named mean_var_std.py that leverages NumPy to compute the mean, variance, standard deviation, max, min, and sum of the rows, columns, and elements in a 3x3 matrix. 

Build a Chatbot in Python from Scratch!

NumPy Variance and Standard Deviation Basics

Before diving into matrix operations, let's cover the basics of calculating variance and standard deviation using NumPy. The functions np.var() and np.std() are key players here.

import numpy as np

# Sample array

data = np.array([1, 2, 3, 4, 5])

# Calculate Mean 

Mean = np.mean(data) 

# Calculate variance

variance = np.var(data)

# Calculate standard deviation

std_dev = np.std(data)

#Printing the results 

print(f”Mean: {Mean}”)

print(f"Variance: {variance}")

print(f"Standard Deviation: {std_dev}")

How to Calculate NumPy Variance of a Matrix? 

To calculate the variance of a matrix, we can use the same np.var() function along the desired axis. For a 2D matrix, specifying axis=None computes the variance of all elements, while axis=0 and axis=1 give row-wise and column-wise variances, respectively.

Step 1 - Importing Library

import numpy as np

We have only imported numpy which is needed.

Step 2 - Creating a matrix

We have created a matrix by using np.array with different values.

    matrixA = np.array([[1, 2, 3, 23],

                       [4, 5, 6, 25],

                       [7, 8, 9, 28],

                       [10, 11, 12, 41]])

Learn to Build a Neural network from Scratch using NumPy

Step 3 - Calculate Mean, Median, Mode, Standard Deviation, Variance in Python using NumPy

We have calculated mean, median , variance and standard deviation by using numpy functions for a matrix.

    print("Median: ", np.median(matrixA))

   print("Mean: ", np.mean(matrixA))

   print("Variance: ", np.var(matrixA))

   print("Standrad Dev: ", np.std(matrixA))

So the output comes as

Median:  8.5

Mean:  12.1875

Variance:  118.27734375

Standrad Dev:  10.875538779757076

For Example —> 

Now, let's create a Python file named mean_var_std.py with a function called calculate() that utilizes NumPy to output various statistics for a given 3x3 matrix. 

# mean_var_std.py

import numpy as np

def calculate(matrix):

    # Calculate mean, variance, std, max, min, and sum along rows, columns, and elements

    row_stats = {

        "Mean": np.mean(matrix, axis=1),

        "Variance": np.var(matrix, axis=1),

        "Std Deviation": np.std(matrix, axis=1),

        "Max": np.max(matrix, axis=1),

        "Min": np.min(matrix, axis=1),

        "Sum": np.sum(matrix, axis=1)

    }

    col_stats = {

        "Mean": np.mean(matrix, axis=0),

        "Variance": np.var(matrix, axis=0),

        "Std Deviation": np.std(matrix, axis=0),

        "Max": np.max(matrix, axis=0),

        "Min": np.min(matrix, axis=0),

        "Sum": np.sum(matrix, axis=0)

    }

    elem_stats = {

        "Mean": np.mean(matrix),

        "Variance": np.var(matrix),

        "Std Deviation": np.std(matrix),

        "Max": np.max(matrix),

        "Min": np.min(matrix),

        "Sum": np.sum(matrix)

    }

    return row_stats, col_stats, elem_stats

# Example usage

matrix_example = np.array([[1, 2, 3],

                           [4, 5, 6],

                           [7, 8, 9]])

result = calculate(matrix_example)

print("Row-wise Stats:", result[0])

print("Column-wise Stats:", result[1])

print("Element-wise Stats:", result[2])

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python

Practice More NumPy Matrix Operations with ProjectPro! 

NumPy simplifies statistical computations, providing efficient and easy-to-use functions for calculating variance and standard deviation. However, true mastery of concepts comes through practical experience. ProjectPro, an all-in-one platform with a rich repository of 250+ projects in data science and big data, provides a unique opportunity for hands-on learning. By applying the techniques learned in this tutorial to real-world projects on ProjectPro, you can solidify your understanding and elevate your expertise in NumPy matrix operations.

Download Materials

What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

End-to-End ML Model Monitoring using Airflow and Docker
In this MLOps Project, you will learn to build an end to end pipeline to monitor any changes in the predictive power of model or degradation of data.

Skip Gram Model Python Implementation for Word Embeddings
Skip-Gram Model word2vec Example -Learn how to implement the skip gram algorithm in NLP for word embeddings on a set of documents.

Text Classification with Transformers-RoBERTa and XLNet Model
In this machine learning project, you will learn how to load, fine tune and evaluate various transformer models for text classification tasks.

OpenCV Project for Beginners to Learn Computer Vision Basics
In this OpenCV project, you will learn computer vision basics and the fundamentals of OpenCV library using Python.

AWS MLOps Project to Deploy a Classification Model [Banking]
In this AWS MLOps project, you will learn how to deploy a classification model using Flask on AWS.

MLOps using Azure Devops to Deploy a Classification Model
In this MLOps Azure project, you will learn how to deploy a classification machine learning model to predict the customer's license status on Azure through scalable CI/CD ML pipelines.

Personalized Medicine: Redefining Cancer Treatment
In this Personalized Medicine Machine Learning Project you will learn to classify genetic mutations on the basis of medical literature into 9 classes.

Classification Projects on Machine Learning for Beginners - 2
Learn to implement various ensemble techniques to predict license status for a given business.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.