generate an array of numbers with conditions

Hi, looking to generate an array of zeroes of a specific length (that I can control) with an n number of values being nonzero. I then want a n amount of those zeroes to be randomly replaced with fractions (which all sum up to 1), but those fractions should have a lower and an upper bound that I control.

​

example: generate array of 15 zeroes:

in:
arry1 = np.zeros((15,), dtype=int)
out:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

I then want to end up with an n number of these zeroes to be a random fraction of 1 with a lower and upper bound that I can control, but those fractions need to all add up to 1.

example of the result I want: (I set just 5 to be replaced with fractions and lower bound to be 0.05 and upper to be 0.5 )

array([0, 0.3, 0, 0.06, 0, 0.15, 0.15, 0, 0, 0, 0, 0.34, 0, 0, 0])

What I tried:

I figured I could generate another array with the random numbers I could insert into the first one:

in:
weights = np.random.rand(5)
weights = weights/sum(weights)
out:
array([0.24346125, 0.38024931, 0.07538368, 0.25831351, 0.04259225])

But before I solve how to randomly replace the zeros in arry1 with the one above, I have to figure out how to control the lower and upper bound of the "weights" array too

Posted Jun 7, 2022, 10:59 AM UTC

210
Loading comments…