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

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Build CI/CD Pipeline for Machine Learning Projects using Jenkins
In this project, you will learn how to create a CI/CD pipeline for a search engine application using Jenkins.

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.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Image Classification Model using Transfer Learning in PyTorch
In this PyTorch Project, you will build an image classification model in PyTorch using the ResNet pre-trained model.

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.