【问题标题】:Generate random samples with specified properties from a population in Python在 Python 中从总体中生成具有指定属性的随机样本
【发布时间】:2022-01-22 11:33:56
【问题描述】:

假设我有一个按以下比例(%)除以国籍的人口:

percentages = {'Germany': 0.4, 'France': 0.25, 'Greece': 0.15, 'Poland': 0.1, 'Norway': 0.05, 'Others': 0.05}

现在我需要从这个总体中生成样本。 Python 中有没有办法从总体中生成大小为 n 的样本?

例如,如果n = 50,我希望有类似的东西:

sample = {'Germany': 22, 'France': 10, 'Greece': 8, 'Poland': 6, 'Norway': 3, 'Others': 1}

【问题讨论】:

标签: python random sample


【解决方案1】:

随机有一个内置方法

import random
random.choices(
     population=list(percentages.keys()), 
     weights=list(percentages.values()),
     k=50
)

那么你可以这样做:

import random
percentages = {'Germany': 0.4, 'France': 0.25, 'Greece': 0.15, 'Poland': 0.1, 'Norway': 0.05, 'Others': 0.05}

r = random.choices(
     population=list(percentages.keys()),
     weights=list(percentages.values()),
     k=50
)

sample = {key: 0 for key in percentages}
for key in r:
    sample[key] += 1

print(sample)

可能不是最有效的方法,但确实有效。

【讨论】:

  • 可以使用collections.Counter 代替循环。不错的答案+1
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多