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

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

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.

MLOps Project to Deploy Resume Parser Model on Paperspace
In this MLOps project, you will learn how to deploy a Resume Parser Streamlit Application on Paperspace Private Cloud.

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python
In this machine learning regression project, you will learn to build NumPy Regression Models (Linear Regression, Ridge Regression, Lasso Regression) from Scratch.

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.

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)