本文主要是介绍python numpy的sum函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
顾名思义,sum函数的作用就是用于求和,不过特殊的在于能对矩阵按行和列进行求和。
sum的参数比较多,我们仅对前面两个参数进行说明。
Help on function sum in module numpy.core.fromnumeric:sum(a, axis=None, dtype=None, out=None, keepdims=<class 'numpy._globals._NoValue'>)Sum of array elements over a given axis.Parameters----------a : array_likeElements to sum.axis : None or int or tuple of ints, optionalAxis or axes along which a sum is performed. The default,axis=None, will sum all of the elements of the input array. Ifaxis is negative it counts from the last to the first axis... versionadded:: 1.7.0If axis is a tuple of ints, a sum is performed on all of the axesspecified in the tuple instead of a single axis or all the axes asbefore.
如果只有一个入参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):即每一列为一个元素,以行方向相加
这篇关于python numpy的sum函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!