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…
- CourseProbability and Statistics in python
- Lesson20 of 35
- Video21 min
- FormatJupyter notebook · 18 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome 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()
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)
# Generating several random numbers at once
random_numbers = np.random.rand(5)
print("Random numbers:", random_numbers)
# Getting reproducible results with 'random seed'
np.random.seed(42)
print(np.random.rand(3))
# Simulate a coin flip: heads (1) or tails (0)
coin = np.random.randint(0, 2)
print("Heads" if coin == 1 else "Tails")
# Simulate rolling a fair six-sided die
die = np.random.randint(1, 7)
print("Rolled:", die)
# Generate random integers: useful for games and sampling
sample = np.random.randint(10, 20, size=5)
print("Random numbers from 10 to 19:", sample)
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)
# 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)
# 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)
# 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)
# Poisson distribution: Counting rare events per period
calls = np.random.poisson(lam=2, size=10)
print("Random number of daily calls (average 2):", calls)
# 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])
# Exponential distribution: Time until something happens
exp_data = np.random.exponential(scale=5, size=10)
print("Random waiting times:", exp_data)
Quick Challenge! Practice with random numbers#
Can you...
- Generate 20 random integers between 1 and 100?
- Calculate the mean and standard deviation?
- 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)
# 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())
# 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)
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.



