# NumPy 数学操作和广播

Jinku Hu 2023年1月30日 2018年7月14日

## NumPy 四则运算

``````import numpy as np
arrayA = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
arrayB = arrayA.T
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

arrayB = arrayA.T
#array([[1, 4, 7],
#       [2, 5, 8],
#       [3, 6, 9]])

arrayA + arrayB
#array([[ 2,  6, 10],
#       [ 6, 10, 14],
#       [10, 14, 18]])

arrayA - arrayB
#array([[ 0, -2, -4],
#       [ 2,  0, -2],
#       [ 4,  2,  0]])

arrayA * arrayB
#array([[ 1,  8, 21],
#       [ 8, 25, 48],
#       [21, 48, 81]])

arrayA / arrayB
#array([[1.        , 0.5       , 0.42857143],
#       [2.        , 1.        , 0.75      ],
#       [2.33333333, 1.33333333, 1.        ]])
``````

``````np.dot(arrayA, arrayB)
#array([[ 14,  32,  50],
#       [ 32,  77, 122],
#       [ 50, 122, 194]])
``````

## NumPy 广播

``````import numpy as np
arrayA = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
arrayA + 1
#array([[ 2,  3,  4],
#       [ 5,  6,  7],
#       [ 8,  9, 10]])
``````

``````arrayA + np.array([[1,1,1],[1,1,1],[1,1,1]])
``````

NumPy 广播还可以有下面的用法

### 两矩阵具有某一相同的维度，而另外一维其中一矩阵长度为 1

``````arrayC = np.array([10, 11, 12])
arrayA + arrayC
#array([[11, 13, 15],
#       [14, 16, 18],
#       [17, 19, 21]])
``````

``````arrayD = np.array([[10],[11],[12]])
#array([[10],
#       [11],
#       [12]])
arrayA + arrayD
#array([[11, 12, 13],
#       [15, 16, 17],
#       [19, 20, 21]])
``````
Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.