频道栏目
首页 > 资讯 > Python > 正文

python numpy的sum函数实例解析

18-07-26        来源:[db:作者]  
收藏   我要投稿

顾名思义,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):即每一列为一个元素,以行方向相加

相关TAG标签
上一篇:简单FTP服务器搭建教程
下一篇:Linux的CentOS7系统安装步骤(新手必看)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站