【问题标题】:How to generate random samples from a population in Python?如何在 Python 中从总体中生成随机样本?
【发布时间】:2021-12-30 11:50:12
【问题描述】:

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

从总体中生成 1000 个大小为 50 的随机样本。计算每个样本的平均值(所以你应该有 1000 个平均值)并将它们放入一个列表 norm_samples_50。

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

【问题讨论】:

  • 您是否查看了文档以形成语法? - 它可以帮助你
  • 到目前为止你做了什么?
  • 是的 - 查看文档以形成语法。问题是我无法弄清楚我得到的问题和参数如何适合语法。我还搜索了 YouTube 视频,看看它是如何构建的。作为最后的手段,我真的会选择 Stack。
  • 此类问题的问题是we don't know what you're stuck on。你有 Python 编译器吗?哪个版本?你写过 Python 代码吗?你对编程一无所知吗?你做但是......什么?你得到一个错误?发布错误消息。您没有收到错误,但代码没有达到您的预期?发布您的代码。你期望它做什么?它有什么作用?
  • 感谢 Dour High Arch 的课程。随着我对 Stackoverflow 协议的熟悉,我会将您的建议放在首位。

标签: python random sample


【解决方案1】:

使用 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 没问题,但速度和可靠度不高。

【讨论】:

  • 使用 numpy then Python 内置 sum 效率不高。
  • @user202729 xd xd
【解决方案2】:

这是你想要的吗?

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)

【讨论】:

  • Zak,这是一个很好的答案,但即使您不确定,也不要提出问题或表现出不确定性。你是来提供答案的。还有一个提示,总是创建一个摘要。我以前经常这样做,但这是包含整个答案的答案的一部分,它应该由尽可能少的单词组成。很棒的答案!感谢您的服务和帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多