0

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.

5
  • What is your "array"? A list of lists or a numpy array? Commented Dec 23, 2021 at 17:27
  • Would you mind adding the commas to your lists so they become actual lists Commented Dec 23, 2021 at 17:27
  • Maybe take a look at numpy.vectorize Commented Dec 23, 2021 at 17:28
  • Does this answer your question? Replace numpy array value on condition with random number Commented Dec 23, 2021 at 17:29
  • 'A' is a numpy array. Commented Dec 24, 2021 at 17:00

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

This worked fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.