如何添加矩阵的每一行?

How to add every couple row of matrix?

假设我有一个像

这样的矩阵
a = np.array([[[ 1,  2], [ 3,  4]],
              [[ 5,  6], [ 7,  8]],
              [[ 9, 10], [11, 12]],
              [[13, 14], [15, 16]]])

形状是(4, 2, 2)。我想将前两个和第二个两个矩阵相加。最终输出大小的形状应为 (2, 2, 2),输出应为

output = np.array([[[ 6,  8], [10, 12]],
                   [[22, 24], [26, 28]]])

你可以在下面看到我的尝试:

import numpy as np

a = np.array([[[ 1,  2], [ 3,  4]],
              [[ 5,  6], [ 7,  8]],
              [[ 9, 10], [11, 12]],
              [[13, 14], [15, 16]]])

output = np.add(a[:2], a[2:])

使用重塑将第一个维度分成两个维度,沿第二个轴求和:

a.reshape(2, 2, *a.shape[1:]).sum(axis=1)

您当前的方法等同于 a.reshape(2, 2, *a.shape[1:]).sum(axis=0)。正确的方法是对整个数组的每隔一行进行切片,而不是对整个数组的每个其他块进行切片:

a[::2] + a[1::2]

后一种方法不能很好地概括。如果你必须把每块七块加起来,你会得到

a[::7] + a[1::7] + a[2::7] + a[3::7] + ... + a[6::7]

前一种方法非常灵活,但是:

a.reshape(-1, 7, *a.shape[1:]).sum(axis=1)