0

So I have this array:

TEST = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])

And I want to replace a single random number from the array with 6.

With an exact value I would replace him with:

TEST[0,0] = 6

But since it's a random number that alternates I cannot do that (or maybe I can and just don't know how)

We also have repeated values, so I cannot just pick a value 0 and replace it for 6 since it would replace all the zeros (I think).

So does anyone know how to replace a random number in this specific array? (as an example).

4
  • 1
    What is points? Commented Oct 23, 2022 at 0:57
  • Ops, it's supposed to be "TEST[0:1,0:1] = 6" I will change it, thank you! Commented Oct 23, 2022 at 0:58
  • Just like TEST[0,0] = 6 would replace the value at [0,0], you can pick the row and column indices of the cell to replace and use them as an index into your structure. E.g., TEST[x,y] = 6, with x and y sampled to pick the cell you want to update. Commented Oct 23, 2022 at 0:58
  • Why slices instead of just indexes? Is that what you're asking? I'm not sure I understand the question. BTW, welcome to Stack Overflow! Check out the tour, and How to Ask if you want tips. Commented Oct 23, 2022 at 0:58

2 Answers 2

2

For a slightly different take, numpy.put() allows you to replace and value at the flattened index in an array.

So in the case of:

test = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])

you could pick a number in the range 0 - 15 and put() your value there.

test = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])
i = np.random.randint(np.prod(test.shape))
test.put(i, 100)

Turning test into something like (if i turned out to be 11):

array([[  1,   2,   3,   4,   5],
       [  0,   0,   1,   1,   1],
       [  0, 100,   2,   4,   5]])
Sign up to request clarification or add additional context in comments.

Comments

1

I think you're saying you want to do this;

import numpy as np
import random

test = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])

n1 = random.randrange(test.shape[0])
n2 = random.randrange(test.shape[1])

test[n1][n2] = 6

1 Comment

Yes! It was as simple as that but I wasn't thinking very clear. Thank you very much!

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.