Python – Does anyone have example code of using scipy.stats.distributions


I am struggling to figure out how to use the scipy.distributions package and wondered if anyone could post some example code for me. It appears to do everything I need, I just can't figure out how to use it.

I need to generate two distributions, one log-normal and one poisson. I know the variance and lambda for each.

Links to resources would work just as well.

Best Solution

I assume you mean the distributions in scipy.stats. To create a distribution, generate random variates and calculate the pdf:

Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information.

>>> from scipy.stats import poisson, lognorm
>>> myShape = 5;myMu=10
>>> ln = lognorm(myShape)
>>> p = poisson(myMu)
>>> ln.rvs((10,)) #generate 10 RVs from ln
array([  2.09164812e+00,   3.29062874e-01,   1.22453941e-03,
         3.80101527e+02,   7.67464002e-02,   2.53530952e+01,
         1.41850880e+03,   8.36347923e+03,   8.69209870e+03,
>>> p.rvs((10,)) #generate 10 RVs from p
array([ 8,  9,  7, 12,  6, 13, 11, 11, 10,  8])
>>> ln.pdf(3) #lognorm PDF at x=3

Other methods (and the rest of the scipy.stats documentation) can be found at the new SciPy documentation site.