numpy——陣列的計算

清新的改革之風發表於2020-10-11

1.陣列和數字進行運算——廣播

t5
Out[3]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

執行t5+2的結果

t5+2
Out[4]: 
array([[ 2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13],
       [14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25]])

2.陣列和陣列計算:

t6=np.arange(100,124).reshape((4,6))
t6
Out[6]: 
array([[100, 101, 102, 103, 104, 105],
       [106, 107, 108, 109, 110, 111],
       [112, 113, 114, 115, 116, 117],
       [118, 119, 120, 121, 122, 123]])
t6+t5
Out[7]: 
array([[100, 102, 104, 106, 108, 110],
       [112, 114, 116, 118, 120, 122],
       [124, 126, 128, 130, 132, 134],
       [136, 138, 140, 142, 144, 146]])

2.維度不同相加減

t7=np.arange(0,6)
t7
Out[10]: array([0, 1, 2, 3, 4, 5])
t5
Out[11]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])
t5-t7
Out[12]: 
array([[ 0,  0,  0,  0,  0,  0],
       [ 6,  6,  6,  6,  6,  6],
       [12, 12, 12, 12, 12, 12],
       [18, 18, 18, 18, 18, 18]])

每行都減去了T7

t8
Out[19]: array([[0, 1, 2, 3]])
t8=t8.reshape((4,1))
t8
Out[21]: 
array([[0],
       [1],
       [2],
       [3]])
t5-t8
Out[22]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 5,  6,  7,  8,  9, 10],
       [10, 11, 12, 13, 14, 15],
       [15, 16, 17, 18, 19, 20]])

每列都減去了t8

廣播原則:
如果兩個陣列的後緣維度,既從末尾開始算起的維度的軸長相同,則認為他們是廣播相容的
shape(3,3,3)的陣列不能和shape(3,2)的陣列計算
shape(3,3,2)的陣列可以和shape(3,2)的陣列計算
好處:
如每列的資料減去列的平均值的結果

相關文章