Mathew K Analytics

Lesson 20 · Probability and Statistics in python

Mastering Random Number Generation in Python Using NumPy: Techniques & Applications

In this lesson, you will learn about random number generation using NumPy. Randomness is at the core of probability, simulations, and real-world…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome to Probability & Statistics with Python!#

In this lesson, you will learn about random number generation using NumPy.

Randomness is at the core of probability, simulations, and real-world experiments.

Let's discover how computers help us explore randomness!

# Import essential libraries
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
# Data setup: Let's quickly load a dataset for fun examples
url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
titanic = pd.read_csv(url)
print("Titanic shape:", titanic.shape)
titanic.head()
Titanic shape: (891, 12)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S

What does 'random' mean in Python?#

Random means we can't know the next value ahead of time.

True randomness in computers is hard. Instead, we use algorithms that behave randomly for simulations.

NumPy makes generating these 'pseudo-random' numbers easy and very fast.

# Generating a single random number between 0 and 1
rand = np.random.rand()
print("Random number:", rand)
Random number: 0.66898008013391
# Generating several random numbers at once
random_numbers = np.random.rand(5)
print("Random numbers:", random_numbers)
Random numbers: [0.79830819 0.98766343 0.87895685 0.911479   0.96523027]
# Getting reproducible results with 'random seed'
np.random.seed(42)
print(np.random.rand(3))
[0.37454012 0.95071431 0.73199394]
# Simulate a coin flip: heads (1) or tails (0)
coin = np.random.randint(0, 2)
print("Heads" if coin == 1 else "Tails")
Tails
# Simulate rolling a fair six-sided die
die = np.random.randint(1, 7)
print("Rolled:", die)
Rolled: 5
# Generate random integers: useful for games and sampling
sample = np.random.randint(10, 20, size=5)
print("Random numbers from 10 to 19:", sample)
Random numbers from 10 to 19: [16 19 12 16 17]

Descriptive statistics: Mean and Standard Deviation#

It is hard to describe a list of random numbers all at once.

Two key terms help: mean (average) and standard deviation (spread).

Let us practice finding these with NumPy.

# Generate a list of 100 random numbers from 0 to 100
data = np.random.randint(0, 101, size=100)
mean = np.mean(data)
std = np.std(data)
print("Sample mean:", mean)
print("Sample standard deviation:", std)
Sample mean: 49.63
Sample standard deviation: 29.154984136507426
# What if some data is missing? Handle it safely
data_with_nan = data.astype(float)
data_with_nan[5] = np.nan
mean_nan = np.nanmean(data_with_nan)
print("Mean without nan:", mean_nan)
Mean without nan: 50.121212121212125
# Bernoulli distribution: Like flipping a coin many times
flips = np.random.binomial(1, 0.5, size=20)
print("Coin flips (1=heads, 0=tails):", flips)
Coin flips (1=heads, 0=tails): [0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 0 1]
# Binomial distribution: Counting heads in several coin games
heads = np.random.binomial(n=10, p=0.5, size=5)
print("Number of heads out of 10 flips, 5 experiments:", heads)
Number of heads out of 10 flips, 5 experiments: [5 8 7 6 4]
# Poisson distribution: Counting rare events per period
calls = np.random.poisson(lam=2, size=10)
print("Random number of daily calls (average 2):", calls)
Random number of daily calls (average 2): [1 1 1 4 2 5 0 1 2 0]
# Normal distribution: Most values near the mean
normal_data = np.random.normal(loc=0, scale=1, size=1000)
print("First 10 random values:", normal_data[:10])
First 10 random values: [ 0.72408325 -0.25576464  0.8499212  -1.31132423 -0.87030495 -0.50664322
 -1.30995069  2.94366342 -1.0962658   0.91488432]
# Exponential distribution: Time until something happens
exp_data = np.random.exponential(scale=5, size=10)
print("Random waiting times:", exp_data)
Random waiting times: [ 2.97808437  5.5340853   0.78769538  2.9840407   4.43225658 14.83896662
  1.45529071  2.2255854   2.38500902  4.65116434]

Quick Challenge! Practice with random numbers#

Can you...

  1. Generate 20 random integers between 1 and 100?
  2. Calculate the mean and standard deviation?
  3. Simulate rolling two dice at once, 15 times?

Try your solutions below!

# Mini-project: Simulate random survivors from Titanic
n_trials = 500
prob_survive = titanic['Survived'].mean()
experiments = np.random.binomial(1, prob_survive, size=n_trials)
simulated_survived = np.sum(experiments)
print("Predicted survivors in 500 random draws:", simulated_survived)
Predicted survivors in 500 random draws: 184
# Mini-project: Shuffle the dataset rows with numpy
shuffled = titanic.sample(frac=1, random_state=42).reset_index(drop=True)
print("First 5 shuffled passenger names:")
print(shuffled['Name'].head())
First 5 shuffled passenger names:
0    Moubarek, Master. Halim Gonios ("William George")
1               Kvillner, Mr. Johan Henrik Johannesson
2                          Alhomaki, Mr. Ilmari Rudolf
3                    Harper, Miss. Annie Jessie "Nina"
4                          Nicola-Yarred, Miss. Jamila
Name: Name, dtype: object
# Try it: Input your favorite number and get that many random values
n = int(input("How many random numbers would you like? "))
your_randoms = np.random.rand(n)
print("Here they are:", your_randoms)
Here they are: [0.83268047 0.01103161 0.74954548 0.75867639 0.67837882 0.75626466
 0.84197037]

Recap: Random number generation in Python#

  • We explored how computers simulate randomness.
  • We tried coin flips, dice, distributions, and use cases.
  • We practiced re-using real data and controlling our results.

Randomness enables powerful simulations and science.

Thanks for learning with us!

Before you go...#

Make sure to try the practice prompts, experiment with the examples, and have fun discovering what randomness can do!

If you enjoyed this, please hit like and subscribe on YouTube for more easy data lessons.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.