I want to generate a 2d random array and select some(m)
random indices to alter their values by predefined values(m)
.
For an example here, I want to generate 4 by 4
matrix. Then select 4
random indices and alter their values with [105,110,115,120]
this values.
random_matrix = np.random.randint(0,100,(4,4))
# array([[27, 20, 2, 8],
# [43, 88, 14, 63],
# [ 5, 55, 4, 72],
# [59, 49, 84, 96]])
Now, I want to randomly select 4
indices and alter their values from predefined p_array = [105,110,115,120]
I try to generate all the indices like this:
[
(i,j)
for i in range(len(random_matrix))
for j in range(len(random_matrix[i]))
]
But how to select 4
random indices from this and alter their values from predefined p_matrix
? I couldn't think of any solution because I have to ensure 4
unique random indices where I stuck badly, as randomness haven't that guarantee.
Can we generate random matrix and selecting indices in a single shot? I need that because if the size of m
getting larger and larger than it will be getting slower (current implementation). I have to ensure performance also.
Aucun commentaire:
Enregistrer un commentaire