Numpy 函式介紹
- 導入package numpy, 之後以np縮寫
import numpy as np
初始化矩陣
- 創建矩陣
testArray = np.zeros((x,y)) # 創造x列y行, 內容全為0的矩陣 testArray = np.ones((x,y)) # 同理,x列y行, 內容全為1的矩陣 testArray = np.random.random((x,y)) # x列y行, 內容為0~1之間隨機數字的矩陣 testArray = np.arange(x,y) # 創造一維陣列, 內容為從 x ~ y-1 - 將矩陣重塑成x列y行
testArray = testArray.reshape((x,y))
獲得矩陣範圍內容
- 利用冒號選擇矩陣範圍
testArray[:,0:10] # 第0列到最後一列的 第 0~9 的數 - 若array為n*1的矩陣(或1*n也可?), 則可以用陣列作為index
testArray = testArray.reshape((5,1)) indices = np.array[0,1,2,3] testArray[indices] # 取第0,1,2,3個數 - 可以boolean陣列作為index
boolIndices = np.array[[true,false,true], [false,true,false], [true,false,true]] testArray[boolIndices] # 取array中的第0,2,4,6,8個
矩陣運算
- 矩陣內容運算
np.median(testArray) # 矩陣內容中位數 np.average(testArray) # 矩陣內容平均 np.sum(testArray) # 矩陣內容總和 np.sum(testArray[:,0]) # 矩陣第0欄內容總和 np.std(testArray) # 矩陣內容標準差 # 獲得所有大於矩陣平均值的內容 betterThanAverage = testArray > np.average(testArray) # 得到高於平均值的內容index testArray[betterThanAverage] # 高於平均值的內容 - 複製矩陣
a = testArray # a指向testArray本身, 在改動a時也會改動到testArray a = testArray.copy() # a為testArray的複製版本, 不影響testArray本身 a = np.array(testArray.copy(),dtype=float) # 以float型態複製testArray avg = np.average(a) std = np.std(a) a[(testArray-avg)>std] = avg+std # 將a所有大於平均值+標準差的內容 替換成平均值+標準差 - 矩陣外運算
matrix1 = np.array([[1,2],[3,4]]) matrix2 = np.array([[1,2],[3,4]]) matrix1 * matrix2 # 將兩個矩陣的元素相乘(結果為[1,4],[9,16]) np.dot(matrix1,matrix2) # 矩陣乘法(結果為[19,22],[43,50])