Gitliong
Gitliong

Reputation: 317

How to generate random samples from a population in Python?

I'm trying to address this question:

Generate 1,000 random samples of size 50 from population. Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50.

My guess is I have to use the randn function, but I can't quite guess on how to form the syntax based on the question above. I've done the research and can't find an answer that fits.

Upvotes: 4

Views: 6670

Answers (2)

innicoder
innicoder

Reputation: 2690

A very efficient solution using Numpy.

import numpy


sample_list = []

for i in range(50): # 50 times - we generate a 1000 of 0-1000random - 
    rand_list = numpy.random.randint(0,1000, 1000)
    # generates a list of 1000 elements with values 0-1000
    sample_list.append(sum(rand_list)/50) # sum all elements

Python one-liner

from numpy.random import randint


sample_list = [sum(randint(0,1000,1000))/50 for _ in range(50)]

Why use Numpy? It is very efficient and very accurate (decimal). This library is made just for these types of computations and numbers. Using random from the standard lib is fine but not nearly as speedy or reliable.

Upvotes: 2

Zak Stucke
Zak Stucke

Reputation: 452

Is this what you wanted?

import random

# Creating a population replace with your own: 
population = [random.randint(0, 1000) for x in range(1000)]

# Creating the list to store all the means of each sample: 
means = []

for x in range(1000):
    # Creating a random sample of the population with size 50: 
    sample = random.sample(population,50)
    # Getting the sum of values in the sample then dividing by 50: 
    mean = sum(sample)/50
    # Adding this mean to the list of means
    means.append(mean)

Upvotes: 2

Related Questions