NumPy Tutorial · NumPy Tutorial

NumPy Array Reshape

Learn all about NumPy Array Reshape in this comprehensive tutorial.

5 min read intermediate
  • Reshaping means changing the shape of an array.
  • Yes, as long as the elements required for reshaping are equal in both shapes.
  • The example above returns the original array, so it is a view.
  • You are allowed to have one "unknown" dimension.
  • Flattening array means converting a multidimensional array into a 1D array.

Reshaping arrays

Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in each dimension.

Reshape From 1-D to 2-D

python

Reshape From 1-D to 3-D

python

Can We Reshape Into any Shape?

Yes, as long as the elements required for reshaping are equal in both shapes.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it into a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.

python

Returns Copy or View?

python

The example above returns the original array, so it is a view.

Unknown Dimension

You are allowed to have one "unknown" dimension.

Meaning that you do not have to specify an exact number for one of the dimensions in the reshape method.

Pass -1 as the value, and NumPy will calculate this number for you.

python
Note: Note: We can not pass -1 to more than one dimension.

Flattening the arrays

Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

python
Note: Note: There are a lot of functions for changing the shapes of arrays in numpy flatten, ravel and also for rearranging the elements rot90, flip, fliplr, flipud etc. These fall under Intermediate to Advanced section of numpy.

Module quiz

2 questions
1

Which of the following is true about NumPy Array Reshape?

2

What is the most common pitfall when working with NumPy Array Reshape?

Answer all questions to submit.