↵
【注意:由于numpy是面向数组的,所以其中为我们提供了很多对数组的适应性操作。其中有一个概念叫广播,
总结来说,广播的规则有三个:
-
如果两个数组的维度数dim不相同,那么小维度数组的形状将会在左边补1
-
如果shape维度不匹配,但是有维度是1,那么可以扩展维度是1的维度匹配另一个数组;
-
如果shape维度不匹配,但是没有任何一个维度是1,则匹配引发错误;
】
了解了这个之后,我们来看看这一期的主要内容:
一、数学函数
1、要调用numpy中的数学函数,一定要在numpy包的名称后面接 . 比如:numpy.multiply函数
其他的常见函数可以参见各类python博客或书籍,本文就不再赘述了。
2、下面来介绍一下numpy针对数组而实现的数学函数重载:
在 numpy 中对以下函数进行了运算符的重载,且运算符为 元素级。也就是说,它们只用于位置相同的元素之间,所得到的运算结果组成一个新的数组。
1. numpy.add(x1, x2, *args, **kwargs) Add arguments element-wise.
2. numpy.subtract(x1, x2, *args, **kwargs) Subtract arguments element-wise.
3. numpy.multiply(x1, x2, *args, **kwargs) Multiply arguments element-wise.
4. numpy.divide(x1, x2, *args, **kwargs) Returns a true division of the inputs, element-wise.
5. numpy.floor_divide(x1, x2, *args, **kwargs) Return the largest integer smaller or equal to the division of the inputs.
6. numpy.power(x1, x2, *args, **kwargs) First array elements raised to powers from second array, element-wise.
3、加法函数:numpy.sum
运行机制:
numpy.sum(a[, axis=None, dtype=None, out=None, …]) Sum of array elements over a given axis.
通过不同的 axis ,numpy 会沿着不同的方向进行操作:如果不设置,那么对所有的元素操作;如果 axis=0 ,则沿着纵轴进行操 作; axis=1 ,则沿着横轴进行操作。但这只是简单的二位数组,如果是多维的呢?可以总结为一句话:设 axis=i ,则 numpy 沿着第 i 个下标变化的方向进行操作。
4、乘法函数:numpy.cumsum
运行机制:
numpy.cumsum(a, axis=None, dtype=None, out=None) Return the cumulative sum of the elements along a given axis.
聚合函数 是指对一组值(比如一个数组)进行操作,返回一个单一值作为结果的函数。因而,求数组所有元素之和的函数就是聚合函 数。 ndarray 类实现了多个这样的函数。
5、差值函数:numpy.diff
运行机制:
numpy.diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue) Calculate the n-th discrete difference along the given axis. a. a:输入矩阵 b. n:可选,代表要执行几次差值 c. axis:默认是后一个
The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.
6、四舍五入函数:numpy.around
格式: numpy.around(a, decimals=0, out=None)
7、返回数字符号的逐元素指示函数:numpy.sign
格式: numpy.sign(x, *args, **kwargs)
(逻辑函数请等待,我会尽快更新~~)