Numpy std() – Standard Deviation

Numpy Standard Deviation

Standard Deviation is the measure by which the elements of a set are deviated or dispersed from the mean.

In this tutorial, we will learn how to find the Standard Deviation of a Numpy Array.

In Numpy, you can find the Standard Deviation of a Numpy Array using numpy.std() function.

We shall go through examples covering different scenarios to understand the usage of numpy std() function.

Example 1: Numpy std()

In this example, we shall take a Numpy 1D Array with three elements and find the standard deviation of the array.

Python Program

import numpy as np

#initialize array
A = np.array([2, 1, 6])

#compute standard deviation
output = np.std(A)

print(output)
Run

Output

2.160246899469287

Mathematical Proof

Mean = (2 + 1 + 6)/3
     = 3

Standard Deviation = sqrt( ((2-3)^2 + (1-3)^2 + (6-3)^2)/3 )
                   = sqrt( (1+4+9)/3 )
                   = sqrt(14/3)
                   = sqrt(4.666666666666667)
                   = 2.160246899469287
Run

Example 2: Numpy std() – 2D Array

In this example, we shall take a Numpy 2D Array of size 2×2 and find the standard deviation of the array.

Python Program

import numpy as np

#initialize array
A = np.array([[2, 3], [6, 5]])

#compute standard deviation
output = np.std(A)

print(output)
Run

Output

1.5811388300841898

Mathematical Proof

Mean = (2 + 3 + 6 + 5)/4
     = 4

Standard Deviation = sqrt( ((2-4)^2 + (3-4)^2 + (6-4)^2 + (5-4)^2)/4 )
                   = sqrt( (4+1+4+1)/4 )
                   = sqrt(10/4)
                   = sqrt(2.5)
                   = 1.5811388300841898
Run

Example 3: Numpy std() – Along Axis

You can also find the standard deviation of a Numpy Array along axis.

In this example, we shall take a Numpy 2D Array of size 2×2 and find the standard deviation of the array along an axis.

Python Program

import numpy as np

#initialize array
A = np.array([[2, 3], [6, 5]])

#compute standard deviation
output = np.std(A, axis=0)

print(output)
Run

Output

[2. 1.]

Mathematical Proof

1st element
======================

mean = (2+6)/2 = 4

standard deviation = sqrt( ( (2-4)^2 + (6-4)^2 )/2 )
                   = sqrt( 4 )
                   = 2.0

2nd element
======================

mean = (3+5)/2 = 4

standard deviation = sqrt( ( (3-4)^2 + (5-4)^2 )/2 )
                   = sqrt( 1 )
                   = 1.0
Run

Summary

In this tutorial of Python Examples, we learned how to compute standard deviation of Numpy Array using numpy.std() function, with the help of well detailed examples.