python - 在 numpy 数组中沿轴求和

标签 python numpy multidimensional-array

我想了解这个 ndarray.sum(axis=) 是如何工作的。我知道 axis=0 用于列,axis=1 用于行。 但在 3 维(3 轴)的情况下,很难解释以下结果。

arr = np.arange(0,30).reshape(2,3,5)

arr
Out[1]: 
array([[[ 0,  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]]])

arr.sum(axis=0)
Out[2]: 
array([[15, 17, 19, 21, 23],
       [25, 27, 29, 31, 33],
       [35, 37, 39, 41, 43]])


arr.sum(axis=1)
Out[8]: 
array([[15, 18, 21, 24, 27],
       [60, 63, 66, 69, 72]])

arr.sum(axis=2)
Out[3]: 
array([[ 10,  35,  60],
       [ 85, 110, 135]])

在此示例中,3 轴数组 的形状为 (2,3,5),有 3 行和 5 列。但是,如果我从整体上看这个数组,似乎只有两行(都有 3 个数组元素)。

任何人都可以解释这个总和如何在 3 个或更多轴(维度)的数组上计算。

最佳答案

如果你想保留尺寸你可以指定keepdims:

>>> arr = np.arange(0,30).reshape(2,3,5)
>>> arr.sum(axis=0, keepdims=True)
array([[[15, 17, 19, 21, 23],
        [25, 27, 29, 31, 33],
        [35, 37, 39, 41, 43]]])

否则,您求和的轴将从形状中移除。跟踪这一点的一种简单方法是使用 numpy.ndarray.shape属性:

>>> arr.shape
(2, 3, 5)

>>> arr.sum(axis=0).shape
(3, 5)  # the first entry (index = axis = 0) dimension was removed 

>>> arr.sum(axis=1).shape
(2, 5)  # the second entry (index = axis = 1) was removed

如果需要,您还可以沿多个轴求和(按指定轴的量减少维度):

>>> arr.sum(axis=(0, 1))
array([75, 81, 87, 93, 99])
>>> arr.sum(axis=(0, 1)).shape
(5, )  # first and second entry is removed

关于python - 在 numpy 数组中沿轴求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733479/

相关文章:

python - 如何创建与其自身具有 ManyToMany 关系的 Elixir 类

python - PyCharm 中的 Numpy 导入错误(导入多数组 numpy 扩展模块失败)

c# - Unity 2D Tile Map -- Group Tiles By Type C#

c++ - 如何在方法中返回 C++ 数组指针

php - 如何检查多维数组是否为空?

python - 不规则嵌套 np.where 子句的替代方案

python - pygame.error : video system not initialized. pygame.init() 已经调用

python - Keras 训练在第二个 Epoch 后失败

python - 如何操作 numpy.loadtxt 后的数据?

python - 使用 Python 连接多个 1xn 数组