Reshape an array in Python

Reshaping means changing the shape of an array. We can change the number of elements in each dimension, or we can add or remove dimensions from an array.

In this tutorial, we will use the NumPy library to complete the given task of reshaping the array in Python programming.

First of all start with importing the NumPy library as:

import numpy as np

1-D to the 2-D array

As discussed above, we can change the dimensions of the array, so let’s try to change the 1-D array into a 2-D array.

For this, we need to make a 1-D array first and then we will reshape it in 2-D array.

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

reshaped = arr.reshape(6,2)

[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]

You can change the arguments as you want, like if you want the array of 6 rows and 2 columns the parameter is (6,2). It makes the outermost dimension of 6 arrays each with 2 elements.

So, here we just learned how to convert a 1-D array into a 2-D.

Moving on, now we will try to convert a 1-D array into  3-D.

1-D to a 3-D array

You might be thinking this is so simple, just to increase the parameters from 2 to 3, it will create a 3-D array.

You guessed it right, Coders!

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

reshaped = arr.reshape(2,3,2)

[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]

The outermost dimension will have 2 arrays that contain 3 arrays, each with 2 elements.

Can you reshape in any dimension?

The straightforward answer to this question is NO.


Talking about 8 elements, we can convert it into the 2-D array of 4rows and 2 columns or vice-versa, but if you want to convert it into 2-d array of 3rows and 3columns, it will require 9 elements, but we only have 8, so we encounter error due to this problem.

Multi-dimensional array into 1-D array

We learned how to convert a 1-D array into multi-dimensional. Now the question is Can you convert a multidimensional array into 1-D.

Yes, of course, you can.


It is even easier than converting from 1-D into multi-dimensional. You just need to write reshape(-1), and it’s done. It is also called flattening the arrays.

arr = np.array([[1, 2, 3], [4, 5, 6]])

reshaped = arr.reshape(-1)

[1 2 3 4 5 6]

Do you know?

If you don’t want to specify an exact number for one of the dimensions in a multi-dimensional array, you can use -1 at that place, NumPy will calculate by itself for you. It is referred to as an Unknown Dimension.

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

reshaped = arr.reshape(2, 2, -1)

[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

As here -1 was placed and NumPy found out the exact number of elements to be reshaped i.e. 2.

Thanks for reading the above tutorial. Hope you enjoyed it! Feel free to share your reviews and comment.


Leave a Reply

Your email address will not be published. Required fields are marked *