You can use the moment function from scipy . It calculates the nth central moment of your data.
You can also define your own function, which might look something like this:
def nmoment(x, counts, c, n): return np.sum(counts*(xc)**n) / np.sum(counts)
In this function c meant the point around which the moment is taken, and n is the order. So, to get the variance, you can do nmoment(x, counts, np.average(x, weights=counts), 2) .
source share