新數組的shape屬性應該要與原來數組的一緻,即新數組元素數量與原數組元素數量要相等。一個參數為-1時,那麼reshape函數會根據另一個參數的次元計算出數組的另外一個shape屬性值。
>>> z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],[13, 14, 15, 16]])
>>> z
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> z.reshape(-1)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
>>> z.reshape(-1,2) #我們不知道z的shape屬性是多少,
#但是想讓z變成隻有2列,行數不知道多少,
#通過`z.reshape(-1,2)`,Numpy自動計算出有8行,
#新的數組shape屬性為(8, 2),與原來的(4, 4)配套。
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
[13, 14],
[15, 16]])
>>> z
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> x=z.reshape(-1,2)
>>> x
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
[13, 14],
[15, 16]])
>>> y=x[0] #取出第一行元素
>>> y
array([1, 2])
>>> m=x[:2] ##取出前兩行元素
>>> m
array([[1, 2],
[3, 4]])