Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change array shapes in in numpy?

Tags:

python

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?

like image 570
theQman Avatar asked Jun 05 '15 13:06

theQman


People also ask

Why do we do reshape (- 1 1?

If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).

Can you modify a NumPy array?

Reshape. There are different ways to change the dimension of an array. Reshape function is commonly used to modify the shape and thus the dimension of an array.

How do you get the shape of a NumPy array?

Use the correct NumPy syntax to check the shape of an array. arr = np.array([1, 2, 3, 4, 5]) print(arr. )

How do you reshape an array size?

Use `.reshape()` to make a copy with the desired shape. You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.


2 Answers

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

A.shape = (3,1)
like image 101
alec_djinn Avatar answered Nov 04 '22 14:11

alec_djinn


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
like image 41
Uchiha Madara Avatar answered Nov 04 '22 14:11

Uchiha Madara