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.
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).
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).
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.
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).
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)
.
import scipy as sp
from scipy import stats
stats.moment(counts, moment = 2) #variance
stats.moment returns nth central moment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With