mardi 9 mars 2021

Set K random non-zero elements at each row to zero in a numpy array, vectorized solution

I would like to set K random non-zero elements at each row of a numpy array to zero, in a vectorized manner.

My non-vectorized code is shown below with a typical input and output.

Thanks and regards,

Igal

orig_arr = np.array([[1, 1, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]])
k = 2
for i in range(len(orig_arr)):
    this_row_elements = np.nonzero(orig_arr[i, :])[0]
    sampled = random.sample(list(this_row_elements), k)
    orig_arr[i, sampled] = 0

Before:
    [[1 1 0 1]
     [0 0 1 1]
     [0 1 1 1]
     [1 1 0 0]
     [1 1 1 1]]
After:
    [[0 1 0 0]
     [0 0 0 0]
     [0 0 1 0]
     [0 0 0 0]
     [0 1 0 1]]



Aucun commentaire:

Enregistrer un commentaire