numpy——数组的计算

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)的数组计算
好处:
如每列的数据减去列的平均值的结果

你可能感兴趣的