Home > Net >  Subtract multiple values from row of numpy 2D-array at the same time, using indices
Subtract multiple values from row of numpy 2D-array at the same time, using indices

Time:12-21

I have a 2D numpy array f, for example:

f = np.array(
   [
    [0,0,0],
    [0,0,0],
    [0,0,0]
   ]
)

and another 2D array q, for example:

q = np.array(
   [
    [1,1,1],
    [1,1,1],
    [2,2,2],
    [3,3,3]
   ]
)

Each row in q should be added to a certain row in f, and I only have a list l of indices of rows in f, to which each row in q should be added. The length of l is equal to the number of rows in q. For example:

l = [0,2,0,0]

That means I want to do something like this:

f[l]  = q

which should transform f into:

[
 [6,6,6],
 [0,0,0],
 [1,1,1]
]

i.e. I'm expecting it to do this:

f[0]  = q[0]
f[2]  = q[1]
f[0]  = q[2]
f[0]  = q[3]

but when some indices are repeated in l (index 0 in this example), it only adds the row in q that corresponds to the last repeated index in l. So instead, I get:

[
 [3,3,3],
 [0,0,0],
 [1,1,1]
]

That means it's doing this:

f[2]  = q[1]
f[0]  = q[3]

How can I add multiple rows in q to the same row in f, just having the list l?

CodePudding user response:

Try np.add.at: np.add.at(f, l, q)

  • Related