Calculate moments (mean, variance) of distribution in python

I have two arrays. x is an independent variable, and counts is the number of samples x, such as a histogram. I know that I can calculate the average by defining a function:

def mean(x,counts): return np.sum(x*counts) / np.sum(counts) 

Is there a general function that I can use to calculate every moment from the distribution defined by x and counts? I would also like to calculate the variance.

+5
source share
1 answer

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) .

+5
source

Source: https://habr.com/ru/post/1215401/


All Articles