如何从 Python 中的总体生成随机样本?

How to generate random samples from a population in Python?

我正在尝试解决这个问题:

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.

我的猜测是我必须使用 randn 函数,但我不能完全猜测如何根据上述问题形成语法。我已完成研究,但找不到合适的答案。

这是你想要的吗?

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)

使用 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一行

from numpy.random import randint


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

为什么要使用 Numpy?它非常高效且非常准确(十进制)。这个库就是为这些类型的计算和数字而创建的。使用标准库中的 random 很好,但速度和可靠性都不尽如人意。