我想了解这个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