The Poisson Distribution model the number of times an event happens within a fixed time or space when we know the average number of occurrences. It is used for events that occur independently such as customer arrivals at a store, Website clicks where events happen independently.
numpy.random.poisson()
Method
In Python'sNumPylibrary we can generate random numbers following a Poisson Distribution using thenumpy.random.poisson()
method. It has two key parameters:
- lam: The average number of events (λ) expected to occur in the interval.
- size: The shape of the returned array.
Syntax:
numpy.random.poisson(lam=1.0, size=None)
Example 1: Generate a Single Random Number
To generate a single random number from a Poisson Distribution with an average rate of λ = 5:
Pythonimportnumpyasnprandom_number=np.random.poisson(lam=5)print(random_number)
Output :
5
Example 2: Generate an Array of Random Numbers
To generate multiple random numbers:
Pythonrandom_numbers=np.random.poisson(lam=5,size=5)print(random_numbers)
Output :
[13 6 4 4 10]
Visualizing the Poisson Distribution
To understand the distribution better we can visualize the generated numbers. Here is an example of plotting a histogram of random numbers generated usingnumpy.random.poisson
.
Pythonimportnumpyasnpfromnumpyimportrandomimportmatplotlib.pyplotaspltimportseabornassnslam=2size=1000data=random.poisson(lam=lam,size=size)sns.displot(data,kde=False,bins=np.arange(-0.5,max(data)+1.5,1),color='skyblue',edgecolor='black')plt.title(f"Poisson Distribution (λ={lam})")plt.xlabel("Number of Events")plt.ylabel("Frequency")plt.grid(True)plt.show()
Output:
Poisson DistributionThe image shows a Poisson Distribution withλ=2 displaying the frequency of events. The histogram represents simulated data highlighting the peak at 0 and 1 events, with frequencies decreasing as the number of events increases.