[英]Sum columns in numpy 2D array
I have a 2D NumPy array V
:我有一个 2D NumPy 数组
V
:
import numpy as np
np.random.seed(10)
V = np.random.randint(-10, 10, size=(6,8))
This gives V
as:这给出
V
为:
[[ -1 -6 5 -10 7 6 7 -2]
[ -1 -10 0 -2 -6 9 6 -6]
[ 5 1 1 -9 -2 -6 4 7]
[ 9 3 -5 3 9 3 2 -9]
[ -6 8 3 1 0 -1 5 8]
[ 6 -3 1 7 4 -3 1 -9]]
Now, I have 2 lists, r1
and r2
, containing column indices as follows:现在,我有 2 个列表,
r1
和r2
,包含如下列索引:
r1 = [1, 2, 5]
r2 = [3, 4, 7]
What I want is to add the columns of V
based on the indices pair (r1, r2)
and store it in column indices r1
.我想要的是根据索引对
(r1, r2)
添加V
的列并将其存储在列索引r1
中。 That is, for this case, add columns (1, 3)
, (2, 4)
and (5, 7)
and store them respectively in columns 1
, 2
and 5
of V
.也就是说,对于这种情况,添加列
(1, 3)
、 (2, 4)
和(5, 7)
并将它们分别存储在V
的列1
、 2
和5
中。
It can be done easily like this:可以像这样轻松完成:
V[:, 1] = V[:, [1,3]].sum(axis=1)
V[:, 2] = V[:, [2,4]].sum(axis=1)
V[:, 5] = V[:, [5,7]].sum(axis=1)
which gives V
as:给出
V
为:
[[ -1 -16 12 -10 7 4 7 -2]
[ -1 -12 -6 -2 -6 3 6 -6]
[ 5 -8 -1 -9 -2 1 4 7]
[ 9 6 4 3 9 -6 2 -9]
[ -6 9 3 1 0 7 5 8]
[ 6 4 5 7 4 -12 1 -9]]
My concern is that is there a way we can do it without loops?我担心的是有没有办法不用循环就可以做到这一点? Thanks in advance:)
提前致谢:)
Just add V[:, r2]
at V[:, r2]
, like below:只需在 V[:, r2] 添加
V[:, r2]
V[:, r2]
,如下所示:
V[:, r1] += V[:, r2]
print(V)
Output Output
[[ -1 -16 12 -10 7 4 7 -2]
[ -1 -12 -6 -2 -6 3 6 -6]
[ 5 -8 -1 -9 -2 1 4 7]
[ 9 6 4 3 9 -6 2 -9]
[ -6 9 3 1 0 7 5 8]
[ 6 4 5 7 4 -12 1 -9]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.