Python:NumPy .poisson()
NumPy’s random module includes the .poisson() function, which draws random samples from a Poisson distribution. This distribution models the probability of observing k events in a fixed time interval, given they occur at a constant average rate $\lambda$ and independent of the time since the last event.
The Poisson distribution:
$$f\left(k;\lambda\right) = \frac{\lambda^k e^{-\lambda}}{k!}$$
Syntax
numpy.random.poisson(lam=1.0, size=None)
Parameters:
lam(float, or array_like of floats): The expected number of events occurring over a fixed-time period. Must be>=0.size(int, or tuple of ints, optional): Specifies the output shape. For example,(3, 4)produces a 3×4 array. IfNone, a single sample is returned iflamis scalar; otherwise,np.array(lam).sizesamples are drawn.
Return value:
out(ndarray or scalar): Samples drawn from the Poisson distribution with the specified parameters.
Example 1
This example draws 10 samples from a Poisson distribution with lam=5:
import numpy as np# Generate 10 random samples from a Poisson distribution with λ = 5results = np.random.poisson(5, 10)# Print the samplesprint(results)
This code outputs something similar to this:
[ 7 5 13 5 4 3 2 8 3 4]
Example 2
This example generates a 3×4 matrix of random integers from a Poisson distribution with λ = 5:
import numpy as np# Generate a 3x4 array of Poisson samples with λ = 5results = np.random.poisson(5, (3, 4))print(results)
This code produces an output similar to this:
[[4 4 4 7][1 8 3 4][3 4 8 5]]
Note: The method produces random results so outcomes will vary.
Codebyte Example
This codebyte example generates 10 Poisson-distributed random samples using a lambda value of 5 and prints the result:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Learn to clean, analyze, and visualize data with Python and SQL.
- Includes 15 Courses
- With Certificate
- Beginner Friendly.55 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours