python - 如何在Python中生成在两个边界之间形成正态分布的样本数据?

标签 python numpy statistics normal-distribution

我希望使用 Python 生成一些示例数据。

我想构建一个带有上限、下限和大小参数的函数。然后,它将返回所提供大小的列表,其中包含形成正态分布的上限和下限之间的 float 。

def generate_normal_dist_samples(lower_bound, upper_bound, size):
    # Generate the data here

可以使用 numpy.random.normal 来完成吗?

一个例子是生成员工薪资测试数据。如果我们知道 lower_bound 是 50K,upper_bound 是 500K,我如何生成介于这两者之间但汇总后形成正态分布的样本工资?

最佳答案

前面的答案是正确的,建议使用 truncnorm,但由于问题专门询问 numpy.random.normal,我会用这种 hackish 方法天真地回答它。

请注意,该问题的表述有些不恰当,因为它没有指定正态分布的标准差。

def generate_normal_dist_samples(lower_bound, upper_bound, size, scale=None):
   loc = (lower_bound + upper_bound)/2
   if scale is None:
      scale = (upper_bound-lower_bound)/2
   results = []
   while len(results) < size:
     samples = numpy.random.normal(loc=loc, scale=scale, size=size-len(results))
     results += [sample for sample in samples if lower_bound <= sample <= upper_bound]
   return results

关于python - 如何在Python中生成在两个边界之间形成正态分布的样本数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50375377/

相关文章:

r - 使用 broom::augment 函数获取响应尺度的预测值

python - 单线检查列表中的至少一项是否存在于另一个列表中?

python - 为什么在 locals 中添加 key 实际上会创建变量?

python - numpy向量运算的核心使用上限

python - Python 3 上的 Numpy

python - 在Python中对一系列数据进行分类的最佳方法

python - 在 Python 中从 PDF 中提取页面大小

python - While 循环计数器困惑

numpy - 计算 Hessians w.r.t 高阶变量既不能通过 tf.hessians() 也不能通过 tf.gradients() 工作

algorithm - 隐马尔可夫模型中决定概率的方法有哪些?