np.reshape()基本用法
常用于矩陣規格變換,將矩陣轉換為特定的行和列的矩陣
格式:a1.reshape(x,y,z,…)
注意:將矩陣a1轉變成(x, y,z,…)---->一維長度x,二維長度y,三維長度z,…的矩陣。
場景:matlibplot畫圖時x、y軸需要傳入的是一維,可以用reshape()實現;再例如需要將多維的變成行向量或列向量時也經常要用
numpy.reshape(a, newshape, order='C')[source],參數`newshape`是啥意思?
根據Numpy文檔(https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy-reshape)的解釋:
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, **the value is inferred from the length of the array and remaining dimensions**.
大意是說,數組新的shape屬性應該要與原來的配套,如果等于-1的話,那么Numpy會根據剩下的維度計算出數組的另外一個shape屬性值。
舉幾個例子或許就清楚了,有一個數組z,它的shape屬性是(4, 4)
z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) z.shape (4, 4)
z.reshape(-1)
z.reshape(-1) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z.reshape(-1, 1)
也就是說,先前我們不知道z的shape屬性是多少,但是想讓z變成只有一列,行數不知道多少,通過`z.reshape(-1,1)`,Numpy自動計算出有12行,新的數組shape屬性為(16, 1),與原來的(4, 4)配套。
z.reshape(-1,1) array([[ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11], [12], [13], [14], [15], [16]])
z.reshape(-1, 2)
newshape等于-1,列數等于2,行數未知,reshape后的shape等于(8, 2)
z.reshape(-1, 2) array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8], [ 9, 10], [11, 12], [13, 14], [15, 16]])
同理,只給定行數,newshape等于-1,Numpy也可以自動計算出新數組的列數。