請參考:https://blog.csdn.net/qq_29831163/article/details/90112000#reshape(1%2C-1)%E8%BD%AC%E5%8C%96%E6%88%901%E8%A1%8C%EF%BC%9A
numpy中reshape函數的三種常見相關用法
reshape(1,-1)轉化成1行:
reshape(2,-1)轉換成兩行:
reshape(-1,1)轉換成1列:
reshape(-1,2)轉化成兩列
numpy中reshape函數的三種常見相關用法
- numpy.arange(n).reshape(a, b) 依次生成n個自然數,並且以a行b列的數組形式顯示
np.arange(16).reshape(2,8) #生成16個自然數,以2行8列的形式顯示
import numpy as np
arr = np.arange(16).reshape(2,8)
print(arr)
結果:
[[ 0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]]
- mat (or array).reshape(c, -1) 必須是矩陣格式或者數組格式,才能使用 .reshape(c, -1) 函數, 表示將此矩陣或者數組重組,以 c行d列的形式表示
arr.reshape(4,-1) #將arr變成4行的格式,列數自動計算的(c=4, d=16/4=4)
#將arr變成4行的格式,列數自動計算的(c=4, d=16/4=4)
arr2 = arr.reshape((4,-1))
print(arr2)
結果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
#reshape(2,-1)轉換成兩行:
arr5 = arr.reshape((2,-1))
print(arr5)
結果:
[[ 0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]]
#reshape(-1,2)轉化成兩列:
arr6 = arr.reshape((-1,2))
print(arr6)
結果:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]]
- numpy.arange(a,b,c) 從 數字a起, 步長為c, 到b結束,生成array
- numpy.arange(a,b,c).reshape(m,n) :將array的維度變為m 行 n列。
#reshape(1,-1)轉化成1行:
arr3 = arr.reshape(1,-1)
print(arr3)
結果:[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
#reshape(-1,1)轉化成1列:
arr4 = arr.reshape(-1,1)
print(arr4)
結果:
[[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]
[13]
[14]
[15]]