How to randomly set elements in numpy array to 0

后端 未结 4 2200
我在风中等你
我在风中等你 2021-02-19 06:33

First I create my array

myarray = np.random.random_integers(0,10, size=20)

Then, I want to set 20% of the elements in the array to 0 (or some o

4条回答
  •  暖寄归人
    2021-02-19 07:02

    Use np.random.permutation as random index generator, and take the first 20% of the index.

    myarray = np.random.random_integers(0,10, size=20)
    n = len(myarray)
    random_idx = np.random.permutation(n)
    
    frac = 20 # [%]
    zero_idx = random_idx[:round(n*frac/100)]
    myarray[zero_idx] = 0
    

提交回复
热议问题