Random sampling

Random sampling

import matplotlib.pyplot as plt
import random

Say we have a dataset and we want to grab a number of random samples from that dataset. Let’s start by grabbing one random sample through the choice() function.

# Generate numbers from 0 to 9
data = [i for i in range(10)]
random.choice(data)
0

To grab multiple samples, we have the option to allow our samples to be duplicated. We use the choices() function for that.

# Random choices with duplicates
random.choices(data, k=5)
[1, 2, 8, 0, 0]

To grab unique samples from the data (no duplicates), we use the sample() function.

# Random choices without duplicates
random.sample(data, 5)
[0, 8, 7, 4, 3]