Assume we have an array of length 1000 where all of its values are 1, i.e., it is like [1,1,1,1,1,1,…,1,1,1,1]. Now suppose we need to convert this array to a block array such that 25% of the array would be block of 0 instead of 1 located uniformly at random positions. Therefore, the final array would be something like [1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,…,1,1,1,0,0,0].
Is there any efficient way in python/numpy to do this?
You can create random indices list with the length of 0.25 main list then change that indices in main list to 0.
>>> l=np.ones(30)
>>> length=len(l)
>>> rand=np.arange(int(0.25*length))
>>> np.random.shuffle(rand)
>>> l[rand]=0
>>> l
array([0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
0, 0, 1, 1, 1, 0, 1])
And more precise you can do :
main_list[np.random.choice(length,int(0.25*length),replace=False)]=0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With