Search code examples
pythonnumpyprobability

Creating a probability distribution using Numpy in Python3.6


I'm trying to create a probability distribution using Numpy in the following way:

x = 3
pat = [0.20, 0.30, 1.30]
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat)))

And this works fine. The problem is that my "population" is evolving and starts at 0, meaning that this may happen:

x = 3
pat = [0, 0, 0]
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat)))

At which point, python is dividing by 0 and returns an error. Is there anyway to create a probability distribution of this kind?


Solution

  • In one line it will look like this:

    z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat))) if any(pat) else numpy.random.choice(x)