Random sampling might sound complicated, but it’s a super useful skill when working with data in Python. It helps you pick out bits of information without going through everything. Python’s got this cool toolbox called the random
module that makes random sampling a breeze.
Understand How to Use Random Sampling in Python
This tutorial provides different ways of random sampling and explains them with examples. By the end, you’ll learn how to randomly pick elements, shuffle things around, and even simulate random processes. Let’s begin to explore this topic.
Introduction to Random Sampling
Random sampling helps us make sense of big data sets without going crazy. Think of it as grabbing a bunch of random samples to understand the whole thing better. It’s like tasting a bit of soup to know if it needs more salt.
10 Python Methods for Random Sampling
Python has a special “random” module that provides several functions for random sampling. It’s like a bag of tricks for grabbing things randomly, from numbers to items in a list.
Simple Random Sampling
Use random.choice()
when you want one thing randomly picked from a bunch of things. It’s like closing your eyes and pointing to something on a menu.
import random as rnd
samples = [0.1, 0.11, 0.111, 0.1111, 0.1111]
sample = rnd.choice(samples)
print("You randomly chose:", sample)
Here, random choice() picks one thing from the list of samples. Easy, right?
Sampling Without Replacement
If you need a few things, but each one has to be unique, use random.sample()
. It’s like picking a few unique candies from a big jar.
import random as rnd
samples = [0.1, 0.12, 0.13, 0.13, 0.14]
sample = rnd.sample(samples, 3)
print("You got these unique things:", sample)
Here, random.sample()
gives you a few unique things from the list samples
.
Sampling With Replacement
When it’s okay to pick the same thing more than once, use random.choices()
. It’s like opening a bag of candies, taking one, and returning it for the next round.
import random as rnd
samples = [1/1, 1/2, 1/3, 1/4, 1/5]
sample = rnd.choices(samples, k=3)
print("You randomly got these, and maybe some twice:", sample)
Here, random.choices()
lets you pick a few things, and it might choose the same thing more than once.
Random Integer Generation
This is a way to select random whole numbers within a range. It’s a part of random sampling, which picks items randomly from a group.
For random whole numbers, use random.randint()
. It’s like rolling a dice and getting a number between two others.
import random as rnd
rand_int = rnd.randint(1, 10)
print("You rolled the dice and got:", rand_int)
Here, random.randint()
gives you a random number between 1 and 10.
Random Float Generation
If you need random decimal numbers, use random.uniform()
. It’s like guessing a number between two others, even if they’re not whole.
import random as rnd
rand_ft = rnd.uniform(0.0, 1.0)
print("You guessed a random decimal between 0.0 and 1.0:", rand_ft)
Here, random.uniform()
gives you a random decimal between 0.0 and 1.0.
Shuffling Sequences
To mix up the order of things in a list, use random.shuffle()
. It’s like shuffling a deck of cards.
import random as rnd
samples = [1, 11, 111, 1111, 1111]
rnd.shuffle(samples)
print("You shuffled the list and got:", samples)
Here, random.shuffle()
mixes up the order of the list samples
.
Seed for Reproducibility
If you want to get the same random results every time, use random.seed()
. It’s like setting a magic number so that your randomness is predictable.
import random as rnd
random.seed(42)
rand_int = rnd.randint(1, 10)
print("With the magic number 42, you got:", rand_int)
Here, random.seed(42)
guarantees you get the same random results every time you run the code.
Custom Probability Distributions
Custom probability distributions determine how items are selected through random sampling, reflecting specific conditions. When you want some things to be more likely than others, use random.choices()
with the weights
parameter. It’s like making a game where you’re more likely to roll a certain number.
import random as rnd
samples = [1**1, 2**2, 3**3, 4**4, 5**5]
weights = [0.1, 0.2, 0.3, 0.2, 0.2]
custom_dist = rnd.choices(samples, weights=weights, k=5)
print("You played a game with custom rules and got:", custom_dist)
Here, elements with higher weights are more likely to be chosen.
Monte Carlo Simulation
Monte Carlo simulation uses random sampling to explore the possible outcomes of a complex system. A classic example is estimating the value of π by randomly throwing darts at a target.
import random as rnd
def estimate_pi(num_samples):
inside_circle = 0
for _ in range(num_samples):
x = rnd.uniform(0, 1)
y = rnd.uniform(0, 1)
if x**2 + y**2 <= 1:
inside_circle += 1
return (inside_circle / num_samples) * 4
estd_pi = estimate_pi(100000)
print("You estimated the value of π and got:", estd_pi)
Here, the estimate_pi
function uses random points to approximate the value of π.
Random Sampling Using Pandas
Pandas DataFrame provides a sample() method for random sampling. It’s like grabbing random rows or columns from a table.
import pandas as pd
# Assuming df is a DataFrame
df = pd.DataFrame({
'A': range(1, 11),
'B': range(11, 21),
'C': range(21, 31)
})
rand_sample = df.sample(n=3, random_state=42)
print("You randomly picked these rows from your table:")
print(rand_sample)
Here, df.sample(n=3)
randomly selects 3 rows from the DataFrame df
.
Must Read-
How to Generate Random Integers in Python
How to Generate Random Numbers in Python
Generate a Random Number in 10 Languages
Generate Random Numbers in R Language
Before You Leave
In this guide, we’ve explained the basics of random sampling in Python using the random
module. Whether it’s unique elements, repeated elements, whole numbers, decimals, or custom rules this tutorial covered them all.
Re-read this tutorial multiple times and practice with the given examples. It will gradually help you understand the random sampling concept.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Happy coding,
TechBeamers.