Windy764
Windy764

Reputation: 87

Change multiple labels in np.matrix python?

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.

Upvotes: 0

Views: 874

Answers (2)

IcedLance
IcedLance

Reputation: 426

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.

Upvotes: 1

Space Impact
Space Impact

Reputation: 13255

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]])

Upvotes: 1

Related Questions