如何在Python中从一个群体中产生随机样本?

问题描述 投票:3回答:2

我在Stackoverflow上的第一个问题。所以请大家:好心点:)

我试图解决这个问题。

从人口中生成1000个大小为50的随机样本。计算每一个样本的均值 (所以你应该有 1000 个均值),并把它们放在一个 norm_samples_50 的列表中。"

我的猜测是我必须使用randn函数,但我无法根据上面的问题猜测如何形成语法。我已经做了研究,但找不到合适的答案。任何帮助都将被感激。

python random sample
2个回答
2
投票

A 高效的解决方案,采用 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 从标准库中获得的数据是不错的,但没有那么快或那么可靠。


1
投票

这是你想要的吗?

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)
© www.soinside.com 2019 - 2024. All rights reserved.