简体   繁体   English

使用索引同时从 numpy 二维数组的行中减去多个值

[英]Subtract multiple values from row of numpy 2D-array at the same time, using indices

I have a 2D numpy array f , for example:我有一个二维numpy数组f ,例如:

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

and another 2D array q , for example:和另一个二维数组q ,例如:

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. q中的每一行都应该添加到f中的某一行,而我只有一个f中行的索引列表lq中的每一行都应该添加到该列表中。 The length of l is equal to the number of rows in q . l的长度等于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:应该将f转换为:

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

ie 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 .但是当某些索引在l中重复时(在本例中为索引0 ),它只会添加q中与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 ?如何将q中的多行添加到f中的同一行,仅具有列表l

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM