HomeSoftware EngineeringThe best way to Calculate Variance in Python

The best way to Calculate Variance in Python


If you’ll want to calculate variance in Python, then you are able to do the next.

Choice 1 – Utilizing variance() from Statistics module

import statistics

listing = [12,14,10,6,23,31]
print("Record : " + str(listing))

var = statistics.variance(listing)
print("Variance: " + str(var))

Choice 2 – Utilizing var() from numpy module

import numpy as np

arr = [12,43,24,17,32]

print("Array : ", arr)
print("Variance: ", np.var(arr))

Choice 3 – Utilizing sum() and Record Comprehensions

listing = [12,43,24,17,32]
common = sum(listing) / len(listing)
var = sum((x-average)**2 for x in listing) / len(listing)
print(var)
RELATED ARTICLES

Most Popular

Recent Comments