numpy.sum 官方给的例子里,是一会按列求和,一会按行求和,总有种不确定感(轴axis好术语化呀,没线性代数基础完全不懂呀)那两维以上的怎么办?
先看方法说明
-
numpy.
sum
(
a,
axis=None,
dtype=None,
out=None
)
¶
-
Sum of array elements over a given axis.
Parameters : a : array_like
Elements to sum.
axis : integer, optional
Axis over which the sum is taken. By default axis is None,and all elements are summed.
dtype : dtype, optional
The type of the returned array and of the accumulator in whichthe elements are summed. By default, the dtype of a is used.An exception is when a has an integer type with less precisionthan the default platform integer. In that case, the defaultplatform integer is used instead.
out : ndarray, optional
Array into which the output is placed. By default, a new array iscreated. If out is given, it must be of the appropriate shape(the shape of a with axis removed, i.e.,numpy.delete(a.shape, axis)). Its type is preserved. Seedoc.ufuncs (Section “Output arguments”) for more details.
Returns : sum_along_axis : ndarray
An array with the same shape as a, with the specifiedaxis removed. If a is a 0-d array, or if axis is None, a scalaris returned. If an output array is specified, a reference toout is returned.
See also
-
ndarray.sum
- Equivalent method. cumsum
- Cumulative sum of array elements. trapz
- Integration of array values using the composite trapezoidal rule.
Notes
Arithmetic is modular when using integer types, and no error israised on overflow.
Examples
>>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5])
If the accumulator is too small, overflow occurs:
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128
注意以下例子里的消失(taken)的维
axis=0
>>> import numpy as np
>>> b=np.arange(24).reshape(2,3,4)
>>> b
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]]])
>>> b.sum(axis=0)
array([[12, 14, 16, 18],
[20, 22, 24, 26],
[28, 30, 32, 34]])
(2,3,4)变为(3,4) 下标2的维消失了。和是怎么计算的呢?看下面b的展开样式:
[
[
[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]
],
[
[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23]
]
]
对照 b.sum(axis=0) 结果 ,很容易看出怎么求和的了吧? 下标2的0维消失,却对下标4的2维的元素求和。
<pre name="code" class="python">>>> b.sum(axis=1)
array([[12, 15, 18, 21],
[48, 51, 54, 57]])
(2,3,4)变为(2,4) 下标3的维消失了。和是怎么计算的呢?看下面b的展开样式:
[
[
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]
],
[
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]
]
]
>>> b.sum(axis=2)
array([[ 6, 22, 38],
[54, 70, 86]])
(2,3,4)变为(2,3) 下标4的维消失了。和是怎么计算的呢?看下面b的展开样式:
[
[
[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]
],
[
[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23]
]
]
总结:
看出规律了吗?不是是一会按列求和,一会按行求和,这么简单的!sum(axis=那个维) 那个维就消失,其他维不变,对消失的维求和
python 表示:
b.sum(axis=0) 等同与 b[0,:,:]+b[1,:,:] b.sum(axis=1) 等同与 b[:,0,:]+b[:,1,:]+b[:,2,:] b.sum(axis=2) 等同与 b[:,:,0]+b[:,:,1]+b[:,:,2]+b[:,:,3]