numpy.sum()的使用详解
作者:Leekingsen 时间:2023-01-04 15:19:24
numpy的sum函数可接受的参数是:
sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)
在参数列表中:
a是要进行加法运算的向量/数组/矩阵
axis的值可以为None,也可以为整数和元组
其形参的注释如下:
a : array_like elements to sum.
a:用于进行加法运算的数组形式的元素
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.
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.
根据上文,可知:
axis的取值有三种情况:1.None,2.整数, 3.整数元组。
(在默认/缺省的情况下,axis取None)
如果axis取None,即将数组/矩阵中的元素全部加起来,得到一个和。
Example:
>>> 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
如果axis为整数,axis的取值不可大于数组/矩阵的维度,且axis的不同取值会产生不同的结果。
先以2×2的二维矩阵为例:
>>> np.sum([[0, 1], [0, 5]], axis=0)
array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
在上述例子中
当axis为0时,是压缩行,即将每一列的元素相加,将矩阵压缩为一行
当axis为1时,是压缩列,即将每一行的元素相加,将矩阵压缩为一列(这里的一列是为了方便理解说的,实际上,在控制台的输出中,仍然是以一行的形式输出的)
具体理解如图:
当axis取负数的时候,对于二维矩阵,只能取-1和-2(不可超过矩阵的维度)。
当axis=-1时,相当于axis=1的效果,当axis=-2时,相当于axis=0的效果。
如果axis为整数元组(x,y),则是求出axis=x和axis=y情况下得到的和。
继续以上面的2×2矩阵为例
>>>np.sum([[0,1],[0,5]],axis=(0,1))
>>>6
>>>np.sum([[0,1],[0,5]],axis=(1,0))
>>>6
另外,需要注意的是:如果要输入两个数组/矩阵/向量进行相加,那么就要先把两个数组/矩阵/向量用一个括号括起来,形成一个元组,这样才能够进行相加。因为numpy.sum的运算实现本质是通过矩阵内部的运算实现的。
当然,如果只是向量/数组之间做加法运算,可以直接让两个向量/数组相加,但前提是它们必须为numpy的array数组才可以,否则只是单纯的列表相加
Example:
>>>v1 = [1, 2]
>>>v2 = [3, 4]
>>>v1 + v2
[1, 2, 3, 4]
>>>v1 = numpy.array[1, 2]
>>>v2 = numpy.array[3, 4]
>>>v1 + v2
[4, 6]
来源:https://blog.csdn.net/Leekingsen/article/details/76242244
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python ctypes库2_指定参数类型和返回类型详解
PHP邮箱验证示例教程
浅析Django 接收所有文件,前端展示文件(包括视频,文件,图片)ajax请求
golang之数据验证validator的实现
Python中zip函数如何使用
node.js的事件机制
Python中threading库实现线程锁与释放锁
![](https://img.aspxhome.com/file/2023/1/75311_0s.png)
chr()函数参照表 chr13 chr10 chr34
教你如何编写Vue.js的单元测试的方法
获取键盘键的值 集合 方便监控键盘事件
Python读入mnist二进制图像文件并显示实例
python 遍历可迭代对象的实现方法
MYSQL row_number()与over()函数用法详解
![](https://img.aspxhome.com/file/2023/5/131665_0s.png)
Python同步遍历多个列表的示例
![](https://img.aspxhome.com/file/2023/4/95744_0s.jpg)
Flask 数据库集成的介绍
![](https://img.aspxhome.com/file/2023/3/63983_0s.png)