Home > Software engineering >  Randomly replace cells in a numpy array without replacement
Randomly replace cells in a numpy array without replacement

Time:10-28

I have a 25 x 25 numpy array filled with 0s. I want to randomly replace 0s within the array with 1s, with the number of 0s to be replaced defined by the user and ranging from 1 to 625. How can I do this without replacement becoming an issue given there are two coordinate values, x and y?

Code for generating a 25 x 25 array:

 import numpy as np
 Array = np.zeros((25,25))

Expected result on a 4 x 4 array:

Before

0,0,0,0
0,0,0,0
0,0,0,0
0,0,0,0

After (replace 1)

0,0,0,0
0,0,1,0
0,0,0,0
0,0,0,0

After (replace 16)

1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

CodePudding user response:

Notes:

  • One may generate a unique sequence of random integers from 0 to 624, and mutate the corresponding element of the flattened array according to the generated sequence. Working with the flattened array, in this specific case, enables the development of a (relatively) concise code.

  • One can use np.random.choice together with the argument replace=False to generate a non-repetitive sequence of random numbers. You can see more information on enter image description here

    CodePudding user response:

    Try:

    import random
    
    import numpy as np
    
    howmany = 5
    
    array = np.zeros((25, 25), dtype=int)
    x = set(range(25))
    y = set(range(25))
    
    for num in range(howmany):
        xi = random.choice(list(x))
        yi = random.choice(list(y))
    
        array[xi, yi] = 1
    
        x.discard(xi)
        y.discard(yi)
    
    print(array)
    
  • Related