顾名思义,sum函数的作用就是用于求和,不过特殊的在于能对矩阵按行和列进行求和。
sum的参数比较多,我们仅对前面两个参数进行说明。
Help on function sum in module numpy.core.fromnumeric: sum(a, axis=None, dtype=None, out=None, keepdims=) Sum of array elements over a given axis. Parameters ---------- a : array_like Elements to sum. axis : None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. .. versionadded:: 1.7.0 If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
如果只有一个入参a,则就是简单的求和函数,所有元素相加即可,
>>> a=eye(2) >>> a array([[1., 0.], [0., 1.]]) >>> sum(a) 2.0 >>> b=[1,2,3] >>> sum(b) 6
可见,不管是对于矩阵,还是数组,都是所有元素相加。
如果需要分别对行向量和列向量求和,就需要使用axis这个参数了,
>>> c=array([[1,2,3],[1,2,3],[1,2,3]]) >>> c array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) >>> sum(c, axis=0) array([3, 6, 9]) >>> sum(c, axis=1) array([6, 6, 6]) >>>
由此我们知道,
sum(axis=0):即每一行为一个元素,以列方向相加
sum(axis=1):即每一列为一个元素,以行方向相加