Home > Enterprise >  How to change certain elements in a 2D numpy array at specified col positions?
How to change certain elements in a 2D numpy array at specified col positions?

Time:09-27

I have these info:

a = array([[ 1,  1,  1,  1,  1],
           [ 1,  1,  1,  1,  2],
           [ 1,  1,  1,  1,  3],
           [ 1,  1,  1, 18, 16],
           [ 1,  1,  1, 18, 17]], dtype=int16)
b = np.arange(0,50).reshape(5,10)
change_cols = [1,2,5,7,9]

I would like to change every row of b at columns defined by change_cols with the values of a[:,:,-1] to get:

b = array([[ 0,  1,  1,  3,  4,  1,  6,  1,  8,  1],
           [10,  2,  1, 13, 14,  1, 16,  1, 18,  1],
           [20,  3,  1, 23, 24,  1, 26,  1, 28,  1],
           [30, 16, 18, 33, 34,  1, 36,  1, 38,  1],
           [40, 17, 18, 43, 44,  1, 46,  1, 48,  1]])

Presently I am doing this:

for n, i in enumerate(change_cols):
    b[:,i] = a[:,-(n 1)]

How do I do this in NumPy efficiently w/o using Python's for-loop?

CodePudding user response:

Here is one way to avoid the for loop.

import numpy as np

a = np.array([[ 1,  1,  1,  1,  1],
           [ 1,  1,  1,  1,  2],
           [ 1,  1,  1,  1,  3],
           [ 1,  1,  1, 18, 16],
           [ 1,  1,  1, 18, 17]], dtype=np.int16)
b = np.arange(0,50).reshape(5,10)
change_cols = [1,2,5,7,9]

b[:, change_cols] = a[:, ::-1]

CodePudding user response:

You could do it in one-line with np.arange for the index of the enumerate, and just pass the list of the assignment:

b[:, change_cols] = a[:,-(np.arange(len(change_cols))   1)]

And now:

print(b)

Gives:

[[ 0  1  1  3  4  1  6  1  8  1]
 [10  2  1 13 14  1 16  1 18  1]
 [20  3  1 23 24  1 26  1 28  1]
 [30 16 18 33 34  1 36  1 38  1]
 [40 17 18 43 44  1 46  1 48  1]]
  • Related