简体   繁体   中英

Random non-uniform distribution with given proportion

I have 3 labels: "A","B","C".

I want to generate a random list with 100 elements, 60% of them are "A", 30% are "B", 10% are "C".

How can I do this? (I am new in python, hope this question is not too silly.)


Edit: My question is slightly different from this question: Generate random numbers with a given (numerical) distribution

Just like in the comment, I want exactly 60% of them are "A", not every element has a 60% probability to be "A". So the numpy.random.choice() is not the solution for me.

You can just permute a list. Lets say you create the list

x = list('A'*60 + 'B'*30 + 'C'*10)

Then, you can shuffle this in-place like so:

from random import shuffle
shuffle(x)

Something like that if distributions should be uniform, A will on average occur in 60% of cases, and so other values

import random
res = []
for i in range(0, n_samples):
   r = random.random()
   if(r<=0.6): res.append(A)
   elif(r>0.7): res.append(B)
   elif(r>0.6 and r<=0.7): res.append(C)

If you want exactly 60% to be A, 30% B and 10% C and you know there have to be 100 elements in total, you can do something like the following:

import random

num = 100
prob_a = 0.6
prob_b = 0.3
prob_c = 0.1

As = int(num*prob_a) * 'A'
Bs = int(num*prob_b) * 'B'
Cs = int(num*prob_c) * 'C'

# create a list with 60 As, 30 Bs, and 10 Cs
chars = list(As + Bs + Cs)
random.shuffle(chars)

print("".join(chars))

That'll output something like BAAAAABBCBAABABAAAACAABBAABACAACBAACBBBAAACBAAAABAAABABAAAAABBBABAABAABAACCAABABAAAAAACABBBBCABAAAAA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM