[英]Generate random samples with specified properties from a population in Python
[英]How to generate random samples from a population in Python?
我关于 Stackoverflow 的第一个问题。 所以请:善待:)
我试图解决这个问题:
从总体中生成 1,000 个大小为 50 的随机样本。 计算每个样本的平均值(所以你应该有 1,000 个平均值)并将它们放在一个列表中 norm_samples_50"
我的猜测是我必须使用 randn 函数,但我无法根据上述问题猜测如何形成语法。 我已经完成了研究,但找不到合适的答案。 任何帮助,将不胜感激。
使用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
很好,但速度不快或不可靠。
这是你想要的吗?
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.