numpy数组中沿轴的总和

numpy数组中沿轴的总和

本文介绍了numpy数组中沿轴的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to understand how this ndarray.sum(axis=) works. I know that axis=0 is for columns and axis=1 is for rows.But in case of 3 dimensions(3 axes) its difficult to interpret below result.

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]])

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

Here in this example of 3 axes array of shape(2,3,5), there are 3 rows and 5 columns. But if i look at this array as whole, seems like only two rows (both with 3 array elements).

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

Can anyone please explain how this sum works on array of 3 or more axes(dimensions).

推荐答案

numpy将(2,3,5)数组显示为2个3x5数组的块(3行,5列).或称它们为飞机"(MATLAB会将其显示为5个2x3的块).

numpy displays a (2,3,5) array as 2 blocks of 3x5 arrays (3 rows, 5 columns). Or call them 'planes' (MATLAB would show it as 5 blocks of 2x3).

numpy显示还与嵌套列表匹配-两个子列表的列表;每个都有3个子列表.每个元素长5个元素.

The numpy display also matches a nested list - a list of two sublists; each with 3 sublists. Each of those is 5 elements long.

在3x5 2d情况下,轴0沿3维度求和,从而形成5个元素的数组.用英语对行间和"或沿行列和"的描述有些含糊.重点放在结果,形状变化以及要累加的值上,而不是描述上.

In the 3x5 2d case, axis 0 sums along the 3 dimension, resulting in a 5 element array. The descriptions 'sum over rows' or 'sum along colulmns' are a little vague in English. Focus on the results, the change in shape, and which values are being summed, not on the description.

回到3d情况:

使用axis=0,它沿第一个维度求和,有效地将其删除,剩下3x5的数组. 0+15=16, 1+16=17 etc.

With axis=0, it sums along the 1st dimension, effectively removing it, leaving us with a 3x5 array. 0+15=16, 1+16=17 etc.

轴1,压缩尺寸3尺寸,结果为2x5. 0+5+10=15, etc.

Axis 1, condenses the size 3 dimension, result is 2x5. 0+5+10=15, etc.

第2轴,压缩尺寸5尺寸,结果为2x3,sum((0,1,2,3,4))

Axis 2, condense the size 5 dimenson, result is 2x3, sum((0,1,2,3,4))

您的示例很好,因为这三个维度是不同的,并且更容易看出在求和过程中消除了哪个维度.

Your example is good, since the 3 dimensions are different, and it is easier to see which one was eliminated during the sum.

使用2d时会有一些歧义; 行总和"-表示行被删除或保留了吗?有了3d,就不会有歧义.如果axis = 0,则只能将其删除,而将其余的2个删除.

With 2d there's some ambiguity; 'sum over rows' - does that mean the rows are eliminated or retained? With 3d there's no ambiguity; with axis=0, you can only remove it, leaving the other 2.

这篇关于numpy数组中沿轴的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:14