依据Datewhale的Numpy教程做相应整理
注:默认引用numpy, import numpy as np
1.向量化和广播
概述
向量化和广播是Numpy内部实现的原理。
向量化使得代码更简洁、可读性更强,编写代码时无需使用显式循环,提高整体的效率;
广播为了更友好的使用向量化编程。
详细可参考:Numpy中的广播和数组运算、numpy的广播(Broadcasting)与向量化编程(Vectorization)
广播
Numpy可以转换形状不同的数组,使他们具有相同大小,之后再对他们进行运算。
广播规则:
规则 1:如果两个数组的维度数不相同,那么小维度数组的形状将会在最左边补 1。
规则 2:如果两个数组的形状在任何一个维度上都不匹配,那么数组的形状会沿着维度 为 1 的维度扩展以匹配另外一个数组的形状。
规则 3:如果两个数组的形状在任何一个维度上都不匹配并且没有任何一个维度等于 1, 那么会引发异常。
2.数学函数
2.1算数运算
注意Numpy的广播规则
2.1.1 numpy.add
numpy.add(x1, x2, *args, **kwargs) Add arguments element-wise
等价关系:
y = np.add(x,1)
y = x + 1
2.1.2 numpy.substract
numpy.add(x1, x2, *args, **kwargs) Add arguments element-wise
等价关系
y = np。substract(x,1)
y = x - 1
2.1.3 numpy.multiply
numpy.multiply(x1, x2, *args, **kwargs) Multiply arguments element-wise.
等价关系
y = np.multiply(x, 2)
y = x * 2
2.14 numpy.divide
numpy.multiply(x1, x2, *args, **kwargs) Multiply arguments element-wise.
等价关系
y = np.divide(x, 2)
y = x / 2
2.15 numpy.floor_divide
numpy.floor_divide(x1, x2, *args, **kwargs) Return the largest integer smaller or equal to the division of the inputs.
等价关系:
y = np.floor_divide(x, 2)
y = x // 2
2.16 numpy.power
numpy.power(x1, x2, *args, **kwargs) First array elements raised to powers from second array, element-wise.
等价关系:
y = np.power(x, 2)
y = x ** 2
2.17 numpy.sqrt & numpy.square
- numpy.sqrt(x, *args, **kwargs)
Return the non-negative square-root of an array, element-wise.
等价关系:
y = np.sqrt(x)
y = np.power(x, 0.5)
y = x ** 0.5- numpy.square(x, *args, **kwargs)
Return the element-wise square of the input.
等价关系:
y = np.square(x)
y = np.power(x, 2)
y = x ** 2
2.2 三角函数
2.2.1 numpy.sin & cos & tan & arcsin & arccos & arctan
2.3 指数和对数
2.3.1 numpy.exp & numpy.log
2.4 加法函数、乘法函数
通过不同的参数axis,numpy会沿着不同的方向进行操作:
如果不设置,默认对所有元素操作;
axis=0 ,则沿着纵轴进行操作;
axis=1 ,则沿着横轴进行操作
注:设axis = i;则numpy沿着第i个下标变化的反向进行操作
2.4.1 numpy.sum & numpy.cumsum
2.4.2 numpy.prod & numpy.cumprod (乘积和累乘)
用法同上述 np.sum & np.cumsum
2.4.3 numpy.diff 差值
沿给定轴的第一个差异为out [i] = a [i + 1]-a [i],通过递归使用diff计算更高的差异。
默认axis是最后一个
2.5 四舍五入
2.5.1 numpy.around 舍入
numpy.around(a, decimals = 0)
对给定的小数位数舍入
2.5.2 numpy.ceil & floor 上限 & 下限
2.6 杂项
2.6.1 numpy.clip 裁剪
np.clip(a, a_min, a_max)
给定一个间隔,间隔之外的值将被裁剪到间隔边缘。
2.6.2 numpy.absolute & abs 绝对值
2.6.3 numpy.sign 返回数字符号的逐个=元素指示
3.逻辑函数
3.1 真值测试
3.1.1 numpy.all & any
np.all(a, axis = None) 测试沿给定轴的所有数组元是否为True
np.any(a, axis = None) 测试沿着给定轴的任意数组元素是否为True
3.2 数组内容
3.2.1 numpy.isnan 判断数组元素是否为Nan
3.3 逻辑运算
3.3.1 numpy.logical_not
numpy.logical_not(x, *args, **kwargs)
计算 x 的非真值
3.3.1 numpy.logical_and & logical_or & logical_xor
numpy.logical_and(x1, x2, *args, **kwargs)
计算X1 AND X2 的真值
numpy.logical_or(x1, x2, *args, **kwargs)
计算 X1 OR X2 的真值
numpy.logical_xor(x1, x2, *args, **kwargs)
计算 X1 XOR X2 的真值
3.4 对照
numpy 对照相应函数进行了相应的运算符重载
3.4.1 numpy.greater & greater_equal 大于 & 大于等于
np.greater(x, 2) 等价于 x > 2