如何在numpy中更改数组形状?

the*_*man 7 python numpy

如果我创建一个数组,X = np.random.rand(D, 1)它有形状(3,1):

[[ 0.31215124]
 [ 0.84270715]
 [ 0.41846041]]
Run Code Online (Sandbox Code Playgroud)

如果我创建自己的数组,A = np.array([0,1,2])那么它有形状(1,3)和外观

[0 1 2]
Run Code Online (Sandbox Code Playgroud)

如何强制(3, 1)阵列上的形状A

ale*_*inn 5

numpy已经有一个“重塑”方法,它是numpy.ndarray.shape,您可以使用它来更改数组的形状。

A.shape = (3,1)
Run Code Online (Sandbox Code Playgroud)


Uch*_*ara 5

A=np.array([0,1,2])
A.shape=(3,1)
Run Code Online (Sandbox Code Playgroud)

或者

A=np.array([0,1,2]).reshape((3,1))  #reshape takes the tuple shape as input
Run Code Online (Sandbox Code Playgroud)


jrs*_*rsm 1

您可以直接设置形状,即

A.shape = (3L, 1L)
Run Code Online (Sandbox Code Playgroud)

或者您可以使用调整大小功能:

A.resize((3L, 1L))
Run Code Online (Sandbox Code Playgroud)

或者在创建过程中使用重塑

A = np.array([0,1,2]).reshape((3L, 1L))
Run Code Online (Sandbox Code Playgroud)