python - 在 numpy 中生成大小为 n、均值 = 20、min=2 和 max=25 的整数列表
问题描述
我想生成一个大小为 n、平均值 = 20、最小值 = 2 和最大值 = 25 的整数列表。
并尝试了下面的代码。这非常耗时。
# generate service time with mean = 20, min = 2 and max = 25
def gen_avg(n, expected_avg=20, a=2, b=25):
while True:
l = np.random.randint(a, b, size=n)
avg = np.mean(l)
if avg == expected_avg:
return l
请帮我一些快速的方法
解决方案
您可以生成一个随机列表,然后通过替换大于平均值的数字(如果当前平均值太低)或替换小于平均值的数字(如果当前平均值太高)来稍微调整数字,就像这样
def gen_avg(n, expected_avg=20, a=2, b=25):
l = np.random.randint(a, b, size=n)
while True:
if np.mean(l) == expected_avg:
break
while np.mean(l) > expected_avg:
c = np.random.choice(np.where(l>expected_avg)[0])
l[c] = np.random.randint(a, expected_avg+1)
while np.mean(l) < expected_avg:
c = np.random.choice(np.where(l<expected_avg)[0])
l[c] = np.random.randint(expected_avg, b)
return l
这是假设您不关心从任何特别有趣的发行版中进行生产。
推荐阅读
- laravel - Laravel groupBy 选择多个字段
- reactjs - ESLint 的 extends 属性是否被附加到 overrides 设置中的 extends 属性
- node.js - 错误:包括意外。元素必须是模型,关联......与 sequelize.literal
- php - 禁用操作所需的身份验证
- java - 如何使用地理编码器在 Onsensor 更改方法中使用用户当前坐标
- python - 在python中一次计算和生成多个标准差列但不是以固定的累积顺序
- homebrew - 返回dbt 19.1版本
- python - pdf抓取后拆分列
- r - RMarkdown 在渲染时不会将 $\overline{x}、\bar{y} 转换为符号
- javascript - 邮递员 - 无法在集合级别测试脚本中运行 pm.sendRequest()