Reshaping of Numpy array - Data Science| codin india

 Reshaping of a nd-array can be done using the np.reshape() method. It change the shape of the nd-array without changing the data in it.

We have 2 methods to reshape of nd array:-

            1. np.reshape(array_name, [rows, columns]

            2. array_name.reshape(rows, columns)

In our tutroial, we refer the first method. However the both condition is same.

Let us see an example, where we have 1-D array. We will reshape the array in 2-D array:-

Code:- 

Numpy reshape of array

Output:-
   


Explanation:-  We have a 1-D array([1,2,3,4,5,6]), we reshaped this array using MxN formula.
M means a number of rows and N means number of columns. That means rehape this array using this value of rows and columns.
As you know Array is made up of rows and columns.


When you don't know about any of the shape of axis?

While reshaping of nd-array, if you are unsure about the shape of any axis, just pass first value with -1. Numpy automatically calculates when it sees input -1.

Example 1:

Let us see with example:- 

reshape array without shape


Explanation:-  In this example, we don't know about how many columns it will take when we have 3 rows. when the compiler see the input as -1 it will automatically calculate how many columns required for output and returns value.

Example 2:


Explanation:-  In the case, we don't know about total number of rows required for correct output. So we provide row value as -1. Python calculates and return the output.


What happens when we provide both -1, -1?

Now its time to learn what happens when user provide both rows and columns as -1, -1?

The answer is Python don't allow to do this and throw and error

Code:- 


Here error is that "Python can only specify one unknown dimension". We can't provide both filed as -1 and -1.


Reshape 1-D array into 3-D array?

We can also reshape 1-D array to 3-D array. How can we do it Let see:-

It same is same as earlier methods like when we reshape 1-D to 2-D. For 3-D Array we just have to pass third argument while reshaping. But here is the twist the 3rd argument we pass is act as first argument and 2nd and 3rd will become rows and columns.

So our method will be:- 

np.reshape(array, [ dimension,  rows , columns ])

Let us see code:- 


Output:- 


In this example, we take rows and column's value as 2,3 and dimension value as 1

Look at the output the outermost Array has 2 Array which has 3 rows and 1 columns.


Let us see with another case:- 


Output:-


In this case, the uppermost array has 2 arrays in between and both have 2 rows and 3 columns.


So, I hope you like this tutorial for better understanding you can watch our video tutorial.

SUBSCRIBE to our CODIN INDIA youtube channel

Comments