Randomly zero-out certain percentage of rows in a matrix in python

Let’s say I have matrix that contains 5 rows and 4 columns:

arr = [[1,1,1,1],
       [2,2,2,2],
       [3,3,3,3],
       [4,4,4,4],
       [5,5,5,5]]

and I want to randomly zero=out/mask a certain percentage of this matrix row-wise. So if I set the percentage to be zeroed to 40%. I will get the following:

arr = [[0,0,0,0],
       [2,2,2,2],
       [3,3,3,3],
       [0,0,0,0],
       [5,5,5,5]]

what would be a good way to achieve this? Thanks!

>Solution :

One way to achieve your task is following (set num_zero_rows):

Try it online!

import random

arr = [[1,1,1,1],
       [2,2,2,2],
       [3,3,3,3],
       [4,4,4,4],
       [5,5,5,5]]

num_zero_rows = 2
zero_idxs = set(random.sample(range(len(arr)), num_zero_rows))
arr = [([0] * len(arr[i]) if i in zero_idxs else arr[i])
    for i in range(len(arr))]

print(arr)

Output:

[[0, 0, 0, 0], [2, 2, 2, 2], [0, 0, 0, 0], [4, 4, 4, 4], [5, 5, 5, 5]]

Leave a Reply