04 Oct 2022

Posted on:

20 Jun 2022

0

# reshape function and its properties

I'd be infinitely grateful if I could get some clarification on this. New to python and just recently got introduced to the powerful python package called NumPy.

Question 1

In :

``````#let me illustrate my confusion
#Let's create a 1D array(vector) of type ndarray.
import numpy as np
array_1D = np.array([1,3,45])
array_1D
``````

Out:

``````array([ 1,  3, 45])
``````

In :

``````#let's find the shape of array_1D
array_1D.shape
#My expectation is a 1x3 vector but the output shows something else I don't know how to read or understand.
# I understand that the output is a tuple but what is the order of elements in that tuple?
#Is it (row,columns) or (columns,rows)?

``````

Out:

``````(3,)
``````

Question 2

In :

``````#Let's reshape the array to a 3x1 vector
array_1D.reshape(3,1)
#My expectation is that the dimension will not change and only the shape will
#The reasoning is that the number of "[" in the array equates to the number of dimensions right?
#If so why is output14 displaying a result with 2D

``````

Out:

``````array([[ 1],
[ 3],
])
``````

In :

``````#Let's check the shape of the array after reshaping
array_1D.shape
#No change in shape, but the dimension changed.why?? I mean it is quite the reverse to my thinking.What am I missing or misconstruing?

``````

Out:

``````(3,)
``````
Posted on:

04 Oct 2022

0

- Regarding Q1, generally, shape attribute generates (row, column) structure, however, for a vector it is not defined that way and you need to use 'reshape' method to specifically assign rows and columns shape or simply add another square brackets to convert in to a 2D array like that in below

``````array_1D = np.array([[1, 3, 45]])
print(array_1D.shape)  #this will produce a shape of (1, 3)
``````

``````array_1D = np.array([, , ])
print(array_1D.shape) #this will produce a shape of (3, 1)
``````

- Regarding Q2, yes, reshape converts 1D array into a 2D one by default so it changes both the shape and the dimensions
you can check by using 'ndim' attribute before and after the reshaping