-1

I'd like to generate an int random number between 0 and 1 n number of times. I know the code to generate this:

num_samp = np.random.randint(0, 2, size= 20)

However, I need to specify a condition that say 1 can only appear a number times and the rest should be zeros. For instance if I want 1 to appear only 5 times from the above code, then I would have something like this [0,1,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0]

Can someone help with the code to generate something like this? Thanks

5
  • Hardly random. I'd loop over each value in the array and code in your requirement for max occurrences. Commented Dec 19, 2022 at 15:20
  • After reading answers, I realize that we all replied differently, and it is hard to know who is right. Do you want exactly 5 '1'? Or at most 5? Do you want them to be distributed with 50/50% chance, until there are 5 of them, or to be distributed equally? Commented Dec 19, 2022 at 15:56
  • My answer, for example, gives exactly 5 '1', all places with an equal chance to be 1. So, even the first number do not have a 50/50 chance to be '1' (only 25% chance with N=20,k=5). Scott's answer gives at most 5 '1' (some indices could be equals. As shown in their example, with only 4 '1'), and with a probability of having k '1' quite complicated (not really complicated to compute, but unlikely to be the one you wanted). Your question seems to imply that you want first a 50/50 chance, then a 0% chance to be '1' (like drawing a coin at first, until 5 '1' are drawn, then fill with 0) Commented Dec 19, 2022 at 16:01
  • So, not easy to know for sure what is an acceptable answer for you. Plus, there might be a XY problem here. What is it you are trying to do exactly? Commented Dec 19, 2022 at 16:02
  • Does this answer your question? Binary random array with a specific proportion of ones? Commented Dec 19, 2022 at 20:09

2 Answers 2

3

Then it looks more like shuffling an array with 0 and 1.

N,k=20,5 # Total number of wanted numbers, and of 1 arr=np.zeros((N,), dtype=int) arr[:k]=1 np.random.shuffle(arr) # arr now contains random 0 and 1, with only 5 1. Like this one: # array([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0]) 
Sign up to request clarification or add additional context in comments.

Comments

0

Check numpy.random.choice() It picks a random number from a range and can accept a probability distribution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.