How to randomly set elements in numpy array to 0

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

For others looking for the answer in case of nd-array, as proposed by user holi:

my_array = np.random.rand(8, 50)
indices = np.random.choice(my_array.shape[1]*my_array.shape[0], replace=False, size=int(my_array.shape[1]*my_array.shape[0]*0.2))

We multiply the dimensions to get an array of length dim1*dim2, then we apply this indices to our array:

my_array[np.unravel_index(indices, my_array.shape)] = 0 

The array is now masked.

Tags:

Python

Numpy