Binary random array with a specific proportion of ones?

前端 未结 6 658
-上瘾入骨i
-上瘾入骨i 2020-11-27 03:05

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?

6条回答
  •  伪装坚强ぢ
    2020-11-27 03:45

    You can use numpy.random.binomial. E.g. suppose frac is the proportion of ones:

    In [50]: frac = 0.15
    
    In [51]: sample = np.random.binomial(1, frac, size=10000)
    
    In [52]: sample.sum()
    Out[52]: 1567
    

提交回复
热议问题