1.0 数组相加
首先还是先导入库以及创建3个数组
import numpy as np
arr1 = np.array([1,2,3,4,5])
arr2 = np.array([10,20,30,40,50])
arr3 = np.array([1,2,3,4])
1.1 一维数组和一维数组
arr1+arr2
array([11, 22, 33, 44, 55])
可见相同元素的一维数组对应元素相加就可以 了
那不同元素的一维数组相加会如何呢
arr1+arr3
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-76273358d4ce> in <module>
----> 1 arr1+arr3
ValueError: operands could not be broadcast together with shapes (5,) (4,)
可见到错误ValueError: operands could not be broadcast together with shapes (5,) (4,)说明元素不对等就会报错
1.2 多维数组和多维数组
新建3个多维数组(在0到100取随机数,前行后列)
arr4 = np.random.randint(0,100,(3,4))
arr5 = np.random.randint(0,100,(3,4))
arr6 = np.random.randint(0,100,(4,4))
两个相同格式的数组进行相加
arr4+arr5
array([[ 40, 86, 144, 114],
[146, 110, 80, 138],
[ 22, 118, 104, 109]])
可见数组对应相加
不同格式下的多维数组相加
arr4+arr6
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-0a73565220eb> in <module>
----> 1 arr4+arr6
ValueError: operands could not be broadcast together with shapes (3,4) (4,4)
可见错误ValueError: operands could not be broadcast together with shapes (3,4) (4,4)
说明元素不对等就会报错
1.3 一维数组与多维数组
我们尝试一下一维数组和多维数组相加会如何
arr1+arr6
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-e36670009a5a> in <module>
----> 1 arr1+arr6
ValueError: operands could not be broadcast together with shapes (5,) (4,4)
arr3+arr6
array([[26, 61, 69, 9],[ 6, 87, 96, 36],
[36, 18, 30, 23],
[26, 8, 87, 17]])
arr3+arr4
array([[ 8, 3, 92, 20],[69, 78, 73, 65],
[17, 51, 97, 57]])
1.4 常数和一维数组
arr1+100
array([101, 102, 103, 104, 105])
1.5 常数和高维数组
arr6+100
array([[125, 159, 166, 105],
[105, 185, 193, 132],
[135, 116, 127, 119],
[125, 106, 184, 113]])