Search code examples
python-3.xscipyprobability-densitygamma-distribution

How can I obtain a probability at specific x value in a gamma probability density function in Python scipy?


I can obtain the probability for x in a gamma distribution via the following in python

import numpy as np 
from scipy.stats import gamma

# Gamma distribution
print(gamma.pdf(x=2, a=2, scale=1, loc=0)) # 0.27067

However, this requires creating a new gamma distribution every time I want to get the probably at a specific x.

I like to create a designated gamma distribution my_gamma_dist, then draw from this time and time again for a specific x value.

import numpy as np 
from scipy.stats import gamma

my_gamma_dist = gamma.pdf(x, a=2, scale=1, loc=0)

my_gamma_dist.x = 2 # AttributeError: 'numpy.ndarray' object has no attribute 'x'
print(my_gamma_dist(x=2)) # TypeError: 'numpy.ndarray' object is not callable

I've checked the documentation but I'm still unclear.


Solution

  • You can define the distribution and later call the .pdf method on the values you are looking for, namely:

    from scipy.stats import gamma
    
    g = gamma(a=2, scale=1, loc=0)
    
    x=2
    g.pdf(x)
    0.2706705664732254
    
    x=3
    g.pdf(x)
    0.14936120510359185
    
    # Or pass a list of values to evaluate
    g.pdf([2,3])
    array([0.27067057, 0.14936121])