What is the efficient(probably vectorized with Matlab terminology) way to generate random number of zeros and ones with a specific proportion? Specially with Numpy?
As my case is special for 1/3
, my code is:
import numpy as np
a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)
But is there any built-in function that could handle this more effeciently at least for the situation of K/N
where K and N are natural numbers?
A simple way to do this would be to first generate an
ndarray
with the proportion of zeros and ones you want:Then you can just
shuffle
the array, making the distribution random:Note that this approach will give you the exact proportion of zeros/ones you request, unlike say the binomial approach. If you don't need the exact proportion, then the binomial approach will work just fine.
If I understand your problem correctly, you might get some help with numpy.random.shuffle
You can use
numpy.random.binomial
. E.g. supposefrac
is the proportion of ones:Simple one-liner: you can avoid using lists of integers and probability distributions, which are unintuitive and overkill for this problem in my opinion, by simply working with
bool
s first and then casting toint
if necessary (though leaving it as abool
array should work in most cases).Yet another approach, using
np.random.choice
:Another way of getting the exact number of ones and zeroes is to sample indices without replacement using
np.random.choice
:Out: