How to randomly set elements in numpy array to 0

后端 未结 4 2210
我在风中等你
我在风中等你 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 06:55

    You can calculate the indices with np.random.choice, limiting the number of chosen indices to the percentage:

    indices = np.random.choice(np.arange(myarray.size), replace=False,
                               size=int(myarray.size * 0.2))
    myarray[indices] = 0
    

提交回复
热议问题