是否有一个numpy函数来获取子矩阵的总和? [英] Is there a numpy function to get the sum of sub matrices?

查看:117
本文介绍了是否有一个numpy函数来获取子矩阵的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到一个数组,它是数组中子矩阵的总和.

I would like to get an array which is the sum of the sub matrices in an array.

例如,假设我们有一个3x3矩阵,其中每个项目都包含一个2x2子矩阵:

For example, lets say we have a 3x3 matrix, where each item contains a 2x2 sub matrix:

matrix = np.array([[[[1,2],[3,4]],     [[5,6],[7,8]],     [[9,10],[11,12]]],
                   [[[13,14],[15,16]], [[17,18],[19,20]], [[21,22],[23,24]]],
                   [[[25,26],[27,28]], [[29,30],[31,32]], [[33,34],[35,36]]]])

如下所示:

[[[[ 1  2]
   [ 3  4]]

  [[ 5  6]
   [ 7  8]]

  [[ 9 10]
   [11 12]]]


 [[[13 14]
   [15 16]]

  [[17 18]
   [19 20]]

  [[21 22]
   [23 24]]]


 [[[25 26]
   [27 28]]

  [[29 30]
   [31 32]]

  [[33 34]
   [35 36]]]]

获得答案的一种方法是使用列表理解

One way to get the answer is using list comprehension

ans = [ [ np.sum(sub_matrices) for sub_matrices in row ] for row in matrix ]

将是:

[[10, 26, 42], [58, 74, 90], [106, 122, 138]]

我想知道是否有更好的方法来获得此结果.也许使用一些内置的numpy函数?

I was wondering if there is a better way to get this result. Maybe using some numpy function built in?

推荐答案

使用 查看全文

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆