我希望使用 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/