[英]How to change array shapes in in numpy?
如果我創建一個數組X = np.random.rand(D, 1)
它的形狀為(3,1)
:
[[ 0.31215124]
[ 0.84270715]
[ 0.41846041]]
如果我創建自己的數組A = np.array([0,1,2])
那么它的形狀為(1,3)
並且看起來像
[0 1 2]
如何強制我的數組A
上的形狀(3, 1)
?
您可以將形狀元組直接分配給numpy.ndarray.shape 。
A.shape = (3,1)
A=np.array([0,1,2])
A.shape=(3,1)
或者
A=np.array([0,1,2]).reshape((3,1)) #reshape takes the tuple shape as input
numpy 模塊有一個reshape
函數,而 ndarray 有一個reshape
方法,它們中的任何一個都應該可以創建一個具有您想要的形狀的數組:
import numpy as np
A = np.reshape([1, 2, 3, 4], (4, 1))
# Now change the shape to (2, 2)
A = A.reshape(2, 2)
Numpy 將檢查數組的大小是否沒有改變,即prod(old_shape) == prod(new_shape)
。 由於這種關系,您可以將 shape 中的一個值替換為-1
並且 numpy 會為您計算出來:
A = A.reshape([1, 2, 3, 4], (-1, 1))
您可以直接設置形狀,即
A.shape = (3L, 1L)
或者您可以使用調整大小功能:
A.resize((3L, 1L))
或在使用重塑創建期間
A = np.array([0,1,2]).reshape((3L, 1L))
您的一維數組的形狀為 (3,):
>>>A = np.array([0,1,2]) # create 1-D array
>>>print(A.shape) # print array shape
(3,)
如果創建形狀為 (1,3) 的數組,則可以使用其他答案或numpy.swapaxes中提到的numpy.reshape :
>>>A = np.array([[0,1,2]]) # create 2-D array
>>>print(A.shape) # print array shape
>>>A = np.swapaxes(A,0,1) # swap 0th and 1st axes
>>>A # display array with swapped axes
(1, 3)
array([[0],
[1],
[2]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.