且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NumPy:对矩阵的每n列求和

更新时间:2022-12-10 21:02:31

这是一种方法;首先将x整形为3D数组,然后在最后一个轴上求和:

Here's one way; first reshape x to a 3D array and then sum over the last axis:

>>> x.reshape(-1, 4, 3).sum(axis=2)
array([[ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30]])