【发布时间】:2021-01-07 21:30:20
【问题描述】:
我正在生成一个 (1109, 8) 数组,该数组具有从一组固定数字 [18, 24, 36, 0] 生成的随机值,我需要确保每行始终包含 5 个零,但它即使在调整了概率的权重之后也没有发生。
我的解决方法代码如下,但想知道是否有其他功能更简单的方法?或者也许通过调整生成器的一些参数? https://numpy.org/doc/stable/reference/random/generator.html
#Random output using new method
from numpy.random import default_rng
rng = default_rng(1)
#generate an array with random values of test duration,
test_duration = rng.choice([18, 24, 36, 0], size = arr.shape, p=[0.075, 0.1, 0.2, 0.625])
# ensure number of tests equals n_tests
n_tests = 3
non_tested = arr.shape[1] - n_tests
for row in range(len(test_duration)):
while np.count_nonzero(test_duration[row, :]) != n_tests:
new_test = rng.choice([18, 24, 36, 0], size = arr.shape[1], p=[0.075, 0.1, 0.2, 0.625])
test_duration[row, :] = np.array(new_test)
else:
pass
print('There are no days exceeding n_tests')
#print(test_durations)
print(test_duration[:10, :])
【问题讨论】: