Skip to content
Related Articles

Related Articles

Compute the mean, standard deviation, and variance of a given NumPy array

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 29 Aug, 2020

 In NumPy, we can compute the mean, standard deviation, and variance of a given array along the second axis by two approaches first is by using inbuilt functions and second is by the formulas of the mean, standard deviation, and variance.

Method 1: Using numpy.mean(), numpy.std(), numpy.var()

Python




import numpy as np
  
  
# Original array
array = np.arange(10)
print(array)
  
r1 = np.mean(array)
print("\nMean: ", r1)
  
r2 = np.std(array)
print("\nstd: ", r2)
  
r3 = np.var(array)
print("\nvariance: ", r3)

Output:

[0 1 2 3 4 5 6 7 8 9]

Mean:  4.5

std:  2.8722813232690143

variance:  8.25

Method 2: Using the formulas 

Python3




import numpy as np
  
# Original array
array = np.arange(10)
print(array)
  
r1 = np.average(array)
print("\nMean: ", r1)
  
r2 = np.sqrt(np.mean((array - np.mean(array)) ** 2))
print("\nstd: ", r2)
  
r3 = np.mean((array - np.mean(array)) ** 2)
print("\nvariance: ", r3)

Output:

[0 1 2 3 4 5 6 7 8 9]

Mean:  4.5

std:  2.8722813232690143

variance:  8.25

Example: Comparing both inbuilt methods and formulas

Python




import numpy as np
  
# Original array
x = np.arange(5)
print(x)
  
r11 = np.mean(x)
r12 = np.average(x)
print("\nMean: ", r11, r12)
  
r21 = np.std(x)
r22 = np.sqrt(np.mean((x - np.mean(x)) ** 2))
print("\nstd: ", r21, r22)
  
r31 = np.var(x)
r32 = np.mean((x - np.mean(x)) ** 2)
print("\nvariance: ", r31, r32)

Output:

[0 1 2 3 4]

Mean:  2.0 2.0

std:  1.4142135623730951 1.4142135623730951

variance:  2.0 2.0


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!