0

I have a matrix as below:

array([[1, 0, 1, 1, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]])

I want to choose randomly 3 position in this matrix, and change labels in those position and the position next to it. The result should be like this:

array([[1, 0, 1, 1, 0],
       [1, 12, 12, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 13, 13, 14, 14],
       [1, 0, 0, 0, 0]])

The labels is choose randomly from list[10, 11, 12, 13, 14, 15]. How can I do this in python? Actually, I tried some methods but it doesn't work properly.

2 Answers 2

1

Using numpy and random libraries:

import random
import numpy as np

a = np.array([[1, 0, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [0, 0, 0, 1, 0],
              [0, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])

f = a.flatten() #to make single dimension array
l = [10, 11, 12, 13, 14, 15] #list of values to be replaced
#np.random.random_integers(0,f.size-1,3) to produce random integers within the max index level
for index in np.random.random_integers(0,f.size-1,3):
    #random.choice(l) to select a random value from list l and replacing original values
    f[index:index+2] = random.choice(l)
    print(index, f[index:index+2], random.choice(l))

7 [14 14] 11
1 [10 10] 14
6 [11 11] 10

#reshaping to the original array shape
a = f.reshape(a.shape)
a

array([[ 1, 10, 10,  1,  0],
       [ 1, 11, 11, 14,  0],
       [ 0,  0,  0,  1,  0],
       [ 0,  0,  0,  0,  0],
       [ 1,  0,  0,  0,  0]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, it's exactly what I need.
1

that would be

for i in range(3):
    r = np.random.randint(array.shape[0])
    c = np.random.randint(array.shape[0])
    _array[r,c:c+2] = _list[np.random.randint(_list.shape[0])]

you can pass ranges start:finish:step or arrays _array[[1,5,7,2]] to create "view"s of a numpy array, which you can then modify as any ordinary array and the changes carry trough to the original array.

1 Comment

Thank you so much, it's very helpful

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.