从值列表中的Python中加权随机数



我正在尝试在1到1000之间创建10,000个随机数的列表。但是我希望数字的80-85%是相同的类别(我的意思是说大约100个数字这些应该出现在随机数列表中的80%的时间),其余的时间约为15-20%。任何想法是否可以在Python/numpy/scipy中完成。谢谢。

可以使用对random.randint()的1个调用来轻松完成此列表,并在正确列表上选择对random.choice()的另一个调用。我假设列表frequent包含100个要选择80%的元素,并且rare包含900元素,以选择20%。

import random
a = random.randint(1,5)
if a == 1:
    # Case for rare numbers
    choice = random.choice(rare)
else:
    # case for frequent numbers
    choice = random.choice(frequent)

这是一种方法 -

a = np.arange(1,1001) # Input array to extract numbers from
# Select 100 random unique numbers from input array and get also store leftovers
p1 = np.random.choice(a,size=100,replace=0)
p2 = np.setdiff1d(a,p1)
# Get random indices for indexing into p1 and p2
p1_idx = np.random.randint(0,p1.size,(8000))
p2_idx = np.random.randint(0,p2.size,(2000))
# Index and concatenate and randomize their positions
out = np.random.permutation(np.hstack((p1[p1_idx], p2[p2_idx])))

让我们在运行后验证 -

In [78]: np.in1d(out, p1).sum()
Out[78]: 8000
In [79]: np.in1d(out, p2).sum()
Out[79]: 2000

最新更新