Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate moments (mean, variance) of distribution in python

I have two arrays. x is the independent variable, and counts is the number of counts of x occurring, like a histogram. I know I can calculate the mean by defining a function:

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

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

like image 762
noob4life Avatar asked Mar 15 '15 17:03

noob4life


People also ask

How to calculate the moment of an array in Python?

scipy stats.moment () function | Python Last Updated : 11 Feb, 2019 scipy.stats.moment (array, axis=0) function calculates the n th moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python).

How do you calculate variance in Python?

Python statistics | variance() Statistics module provides very powerful tools, which can be used to compute anything related to Statistics. variance() is one such function. This function helps to calculate the variance from a sample of data (sample is a subset of populated data).

How do you calculate the moment in SciPy?

scipy.stats.moment (array, axis=0) function calculates the n th moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python). array : Input array or object having the elements to calculate the moment.

How to calculate variance in n-th central moment?

It calculates the n-th central moment of your data. You could also define your own function, which could look something like this: In that function, c is meant to be the point around which the moment is taken, and n is the order. So to get the variance you could do nmoment (x, counts, np.average (x, weights=counts), 2).


2 Answers

You could use the moment function from scipy. It calculates the n-th central moment of your data.

You could also define your own function, which could look something like this:

def nmoment(x, counts, c, n):
    return np.sum(counts*(x-c)**n) / np.sum(counts)

In that function, c is meant to be the point around which the moment is taken, and n is the order. So to get the variance you could do nmoment(x, counts, np.average(x, weights=counts), 2).

like image 71
Curt F. Avatar answered Sep 23 '22 03:09

Curt F.


import scipy as sp
from scipy import stats
stats.moment(counts, moment = 2) #variance

stats.moment returns nth central moment.

like image 37
Tanvir Ahmed Khan Avatar answered Sep 23 '22 03:09

Tanvir Ahmed Khan