4

I am trying to replace specific rows and columns of a Numpy array as given below.

The values of array a and b are as below initially:

a = [[1 1 1 1]
     [1 1 1 1]
     [1 1 1 1]]

b = [[2 3 4 5]
     [6 7 8 9]
     [0 2 3 4]]

Now, based on a certain probability, I need to perform elementwise replacing of a with the values of b (say, after generating a random number, r, between 0 and 1 for each element, I will replace the element of a with that of b if r > 0.8).

How can I use numpy/scipy to do this in Python with high performance?

1 Answer 1

5

With masking. We first generate a matrix with the same dimensions, of random numbers, and check if these are larger than 0.8:

mask = np.random.random(a.shape) > 0.8

Now we can assign the values of b where mask is True to the corresponding indices of a:

a[mask] = b[mask]

For example:

>>> a
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
>>> b
array([[2, 3, 4, 5],
       [6, 7, 8, 9],
       [0, 2, 3, 4]])
>>> mask = np.random.random(a.shape) > 0.8
>>> mask
array([[ True, False, False, False],
       [ True, False, False, False],
       [False, False, False, False]])
>>> a[mask] = b[mask]
>>> a
array([[2., 1., 1., 1.],
       [6., 1., 1., 1.],
       [1., 1., 1., 1.]])

So here where the mask is True (since 0.8 is rather high, we expect on average 2.4 such values), we assign the corresponding value of b.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.