数组加减法
如果两个数组 a 和 b 形状相同,即满足 a.shape == b.shape,那么 a*b 的结果就是 a 与 b 数组对应位相乘,a+b是对应数相加。
>>> a = np.array([1,2,3,4])
>>> b = np.array([10,20,30,40])
>>> a+b
array([11, 22, 33, 44])
>>> a*b
array([ 10, 40, 90, 160])
当 a.shape != b.shape,numpy 将自动触发广播机制,如下:
4x3 的二维数组与长为 3 的一维数组相加,等效于把数组 b 在二维上重复 4 次再运算
>>> a = np.array([[ 0, 0, 0],
... [10,10,10],
... [20,20,20],
... [30,30,30]])
>>> b = np.array([1,2,3])
>>> a+b
array([[ 1, 2, 3],
[11, 12, 13],
[21, 22, 23],
[31, 32, 33]])
>>> a*b
array([[ 0, 0, 0],
[10, 20, 30],
[20, 40, 60],
[30, 60, 90]])
>>> a+2
array([[ 2, 2, 2],
[12, 12, 12],
[22, 22, 22],
[32, 32, 32]])
>>> a[...,1:2]
array([[ 0],
[10],
[20],
[30]])
>>> a+a[...,1:2]
array([[ 0, 0, 0],
[20, 20, 20],
[40, 40, 40],
[60, 60, 60]])
不可计算的情况
>>> a+a[1:3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,3) (2,3)