I am trying to help students visualize the central limit theorem and wanted to do this with simulated data.
I created a population dataset with three variables:
from random import seed
from numpy.random import normal, negative_binomial, binomial
import pandas as pd
data = pd.DataFrame({
"Variable A": normal(0, 1, 100000),
"Variable B": negative_binomial(1, 0.5, 100000),
"Variable C": binomial(1, 0.5, 100000)
})
I then wrote a function that allows me to specify different sample sizes, whether the sampling is conditional, and whether I collect multiple repeated samples.
def iterated_sample(data_frame, type = "random", sample_size = [20, 50, 100, 200, 500, 1000, 2000], number_of_samples = 1):
def single_sample(data_frame, type, sample_size):
if (type == "random"):
single_sample_data = list(map(lambda x: data_frame.sample(x), sample_size))
else:
condition_normal = data_frame["Variable B"] != 0
condition_poisson = data_frame["Variable C"] < 1
single_sample_data = list(map(lambda x: data_frame[condition_normal & condition_poisson].sample(x), sample_size))
return single_sample_data
result = list(map(lambda x: single_sample(data_frame, type, sample_size), range(number_of_samples)))
return result
The problem is that I have a list of list that is kind of a mess. I want to make a list of lists for each sample based on its size.
So my first thought was to jump to list comprehension:
df = iterated_sample(data_frame = data, number_of_samples = 10)
sample_20 = [[el for el in element if len(el) == 20] for element in df]
sample_50 = [[el for el in element if len(el) == 50] for element in df]
...
sample_2000 = [[el for el in element if len(el) == 2000] for element in df]
This is absolutely gross. Is there a way I can avoid having to write a list comprehension for each of the sample sizes? Or how could I adjust iterated_sample()
as it's pretty stupid and can be improved significantly