Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading