Binary random array with a specific proportion of ones?

前端 未结 6 634
-上瘾入骨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:30

    Another way of getting the exact number of ones and zeroes is to sample indices without replacement using np.random.choice:

    arr_len = 30
    num_ones = 8
    
    arr = np.zeros(arr_len, dtype=int)
    idx = np.random.choice(range(arr_len), num_ones, replace=False)
    arr[idx] = 1
    

    Out:

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

提交回复
热议问题