Python - How to add n zeros randomly in an existing matrix?

Viewed 136

i have this array that i generated using the default_rng:

import numpy as np
from numpy.random import default_rng
rng = default_rng(seed=10)
rng = rng.integers(1,20,(5,10))
rng

>>>array([[15, 19,  6,  4, 16, 16, 10,  3, 16, 10],
          [ 3,  3,  8, 14,  8, 16,  1,  9, 10, 19],
          [ 5, 16,  2,  7, 15, 11, 18, 15, 18, 16],
          [ 3, 18, 17,  3, 19, 15,  6,  3,  8, 18],
          [15,  5, 10, 17, 13,  6,  3, 19,  5, 10]], dtype=int64) 

I want to add 10 zeros in this matrix using the generator with seed=5. I thought to create a new array with dimessions [5,10] and to put 10 zeros inside and the rest to be one and then mutliply the two arrays but i have to use the generator so i can't do this.

2 Answers

Try with np.random.choice to choose the index, then set the values at those indexes to 0:

np.random.seed(10)
idx = np.random.choice(np.arange(5*10), size=5, replace=False)

rng.ravel()[idx] = 0

Output:

array([[15, 19,  6,  4, 16, 16, 10,  3, 16, 10],
       [ 3,  3,  8, 14,  8, 16,  1,  9, 10, 19],
       [ 5, 16,  2,  0, 15, 11, 18, 15, 18, 16],
       [ 3, 18, 17,  3, 19, 15,  6,  0,  8, 18],
       [15,  5,  0, 17,  0,  6,  3,  0,  5, 10]])

Of course

idx = np.random.choice(rng.ravel(), 10, replace= False)
print(idx)
rng.ravel()[idx] = 0
rng

Output

       [10 17  3  6 15 15 15 16 15 15]

array([[15, 19,  6,  0, 16, 16,  0,  3, 16, 10],
       [ 0,  3,  8, 14,  8,  0,  0,  0, 10, 19],
       [ 5, 16,  2,  7, 15, 11, 18, 15, 18, 16],
       [ 3, 18, 17,  3, 19, 15,  6,  3,  8, 18],
       [15,  5, 10, 17, 13,  6,  3, 19,  5, 10]], dtype=int64)

So instead of take 10 zeros i take only 6 becaus of 15 appears five times in my idx.

Related