How to change array shapes in in numpy?

Posted on

Question :

How to change array shapes in in numpy?

If I create an array `X = np.random.rand(D, 1)` it has shape `(3,1)`:

``````[[ 0.31215124]
[ 0.84270715]
[ 0.41846041]]
``````

If I create my own array `A = np.array([0,1,2])` then it has shape `(1,3)` and looks like

``````[0 1 2]
``````

How can I force the shape `(3, 1)` on my array `A`?

You ou can assign a shape tuple directly to numpy.ndarray.shape.

``````A.shape = (3,1)
``````

``````A=np.array([0,1,2])
A.shape=(3,1)
``````

or

``````A=np.array([0,1,2]).reshape((3,1))  #reshape takes the tuple shape as input
``````

The numpy module has a `reshape` function and the ndarray has a `reshape` method, either of these should work to create an array with the shape you want:

``````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 will check that the size of the array does not change, ie `prod(old_shape) == prod(new_shape)`. Because of this relation, you’re allowed to replace one of the values in shape with `-1` and numpy will figure it out for you:

``````A = A.reshape([1, 2, 3, 4], (-1, 1))
``````

You can set the shape directy i.e.

``````A.shape = (3L, 1L)
``````

or you can use the resize function:

``````A.resize((3L, 1L))
``````

or during creation with reshape

``````A = np.array([0,1,2]).reshape((3L, 1L))
``````