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).
CodePudding user response:
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]])
CodePudding user response:
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