Home > Mobile >  random number with specific condition in python
random number with specific condition in python

Time:12-20

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

CodePudding user response:

You can try something like this, pick a random sample of indexes (number of 5, in this example) and update those indexes with 1:

a = np.zeros(10)
nz = np.random.choice(np.arange(len(a)), 5)
a[nz] = 1
a

Output:

array([1., 0., 0., 1., 1., 0., 0., 0., 1., 0.])

CodePudding user response:

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])

CodePudding user response:

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

  • Related