theQman
theQman

Reputation: 1780

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?

Upvotes: 12

Views: 41240

Answers (5)

alec_djinn
alec_djinn

Reputation: 10789

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

A.shape = (3,1)

As of 2022, the docs state:

Setting arr.shape is discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.

The current best solution would be

A = np.reshape(A, (3,1))

Upvotes: 7

Wilson Sauthoff
Wilson Sauthoff

Reputation: 480

Your 1-D array has the shape (3,):

>>>A = np.array([0,1,2]) # create 1-D array
>>>print(A.shape) # print array shape
(3,)

If you create an array with shape (1,3), you can use the numpy.reshape mentioned in other answers or numpy.swapaxes:

>>>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]])

Upvotes: 1

Uchiha Madara
Uchiha Madara

Reputation: 1043

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

Upvotes: 6

Bi Rico
Bi Rico

Reputation: 25813

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))

Upvotes: 2

jrsm
jrsm

Reputation: 1695

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))

Upvotes: 1

Related Questions