我需要生成100个随机整数的列表。但是,我需要以仅在5%的情况下才出现大值,而其余值等于0的方式创建值。
这就是我生成此类列表的方式。如何指定较大的值(即5%的情况下应该出现180000左右?
import random
random.sample(range(0, 180000), 100)
例如:
[0, 0, 0, 0, 0, 155000, 0, 0, 0, 0, 0, 0, 0, 0,...,0, 0, 170000]
答案 0 :(得分:2)
您可以这样做:
import numpy as np
nb_vals = 100
large_values = np.arange(150000, 180000, 5000) # from 150 000 to 180 000 by 5 000 steps
your_list = [
0 if np.random.rand() < 0.95 # 95% chance of 0
else np.random.choice(large_values) # 5% chance of random element from large_values
for _ in range(nb_vals) # nb_val independant draws
]
如果您需要另一个可能的值列表,只需将large_values
更改为任何一种一维结构(列表,元组,numpy数组),choice
就会随机选择一个(均匀分布)。探索choice's docs,如果您想要多个值或选择的large_values分配另一个值
如果您希望精确到5%,这是另一种方法:
import numpy as np
nb_vals = 100
ratio = 0.05
large_values = np.arange(150000, 180000, 5000) # from 150 000 to 180 000 by 5 000 steps
target_size = int(ratio * nb_vals) # how many large values do you want
result = np.zeros((nb_vals,))
perm = np.random.permutation(nb_vals)[: target_size] # sample locations
vals = np.random.choice(large_values, size=target_size, replace=True)
# change replace to False if you can't have twice the same large value
result[perm] = vals