jeudi 29 septembre 2022

How to randomly edit elements in a 2D array?

I have a 2D NumPy array in which I would like to randomly replace a few data points with different values. How do to do that for a general NumPy 2D array?

Example: Randomly replace 6 data elements of A having value 1 with value 2.

Input-
A = [
    [1,1,1,1,1,0,0,1,1],
    [1,0,1,0,1,1,0,1,1],
    [0,1,1,1,1,1,1,1,0],
    [1,1,1,1,1,0,0,1,1],
    [1,1,0,0,1,0,0,1,1],
    [1,1,1,1,1,0,0,1,1],
    ]

Output-
A'= [
    [1,1,1,2,1,0,0,1,2],
    [1,0,1,0,1,1,0,1,1],
    [0,1,1,1,1,1,1,1,0],
    [1,1,1,2,1,0,0,1,1],
    [1,1,0,0,1,0,0,1,2],
    [2,1,1,1,1,0,0,1,2],
    ]

How to achieve this using Numpy with few lines of code? Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire