简体   繁体   English

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

[英]How to generate random samples from a population in Python?

My first question on Stackoverflow.我关于 Stackoverflow 的第一个问题。 So please: be kind:)所以请:善待:)

I'm trying to address this question:我试图解决这个问题:

Generate 1,000 random samples of size 50 from population.从总体中生成 1,000 个大小为 50 的随机样本。 Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50"计算每个样本的平均值(所以你应该有 1,000 个平均值)并将它们放在一个列表中 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.我的猜测是我必须使用 randn 函数,但我无法根据上述问题猜测如何形成语法。 I've done the research and cant' find an answer that fits.我已经完成了研究,但找不到合适的答案。 Any help would be appreciated.任何帮助,将不胜感激。

A very efficient solution using Numpy .使用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 Python 单行

from numpy.random import randint


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

Why use Numpy ?为什么使用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.使用标准库中的random很好,但速度不快或不可靠。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM