目錄
numpy中reshape函數的三種常見相關用法
- numpy.arange(n).reshape(a, b) 依次生成n個自然數,並且以a行b列的數組形式顯示
-
np.arange( 16).reshape(2,8) #生成16個自然數,以2行8列的形式顯示
-
# Out:
-
# array([[ 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列的形式表示
-
reshape(m, -1) #改變維度為m行、1列
-
reshape( -1,m) #改變維度為1行、m列
-1的作用就在此: 自動計算d:d=數組或者矩陣里面所有的元素個數/c, d必須是整數,不然報錯)
(reshape(-1, m)即列數固定,行數需要計算)
-
arr=np.arange( 16).reshape(2,8)
-
arr
-
'''
-
out:
-
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
-
[ 8, 9, 10, 11, 12, 13, 14, 15]])
-
'''
-
-
arr.reshape( 4,-1) #將arr變成4行的格式,列數自動計算的(c=4, d=16/4=4)
-
'''
-
out:
-
array([[ 0, 1, 2, 3],
-
[ 4, 5, 6, 7],
-
[ 8, 9, 10, 11],
-
[12, 13, 14, 15]])
-
'''
-
arr.reshape( 8,-1) #將arr變成8行的格式,列數自動計算的(c=8, d=16/8=2)
-
'''
-
out:
-
array([[ 0, 1],
-
[ 2, 3],
-
[ 4, 5],
-
[ 6, 7],
-
[ 8, 9],
-
[10, 11],
-
[12, 13],
-
[14, 15]])
-
'''
-
arr.reshape( 10,-1) #將arr變成10行的格式,列數自動計算的(c=10, d=16/10=1.6 != Int)
-
'''
-
out:
-
ValueError: cannot reshape array of size 16 into shape (10,newaxis)
-
'''
- numpy.arange(a,b,c) 從 數字a起, 步長為c, 到b結束,生成array
- numpy.arange(a,b,c).reshape(m,n) :將array的維度變為m 行 n列。
-
np.arange( 1,12,2)#間隔2生成數組,范圍在1到12之間
-
# Out: array([ 1, 3, 5, 7, 9, 11])
-
-
np.arange( 1,12,2).reshape(3,2)
-
'''
-
Out:
-
array([[ 1, 3],
-
[ 5, 7],
-
[ 9, 11]])
-
'''
reshape(1,-1)轉化成1行:
reshape(2,-1)轉換成兩行:
reshape(-1,1)轉換成1列:
reshape(-1,2)轉化成兩列
本文參考了 Python的reshape(-1,1) 、Numpy中reshape函數、reshape(1,-1)的含義(淺顯易懂,源碼實例)
詳內容可以參看reshape的官方文檔:
鏈接:https://blog.csdn.net/qq_29831163/article/details/90112000