I have a 2D matrix A=[[27 1 63 66 79],[55 20 40 26 68],[42 64 96 27 14]]
. I want to replace every element greater than 20 with a random number. Is there a way to replace it with a new random number every time a entry greater than 20 is detected. I don't want to use the for loop and iterate over each entry.
I am using this A[A>20]= np.random.randint(0,9)
. However in this technique each entry greater than 20 is replaced with a fixed random number.
CodePudding user response:
Assuming you have a numpy array. You need to generate a random array of the same shape.
A = np.where(A>20, np.random.randint(0,9, size=A.shape), A)
Example output:
array([[0, 8, 3, 0, 2],
[1, 4, 7, 5, 1],
[5, 4, 8, 7, 6]])