Skip to Main Content

Python for Basic Data Analysis

Start your data science journey with Python. Learn practical Python programming skills for basic data manipulation and analysis.

Why do we need to reshape arrays?

There may be various reasons to reshape arrays. One of these reasons could be when you want to add an array to another - they need to be of the same size. Recall that the shape of an array is the number of elements in each dimension.

Before reshaping arrays, we have to make sure that the existing array size can indeed match its new size. This means that a 1D array with 11 elements cannot be reshaped into 2D array with 2 rows because 11 cannot be divided by 2 (1 row will have 6 and another row will have 5 elements).

To reshape arrays, we can use the .reshape

Let's create a 3 by 3 array and reshape it into a 1 by 9 array.

How to reshape arrays

How to reshape arrays

Within the parentheses of .reshape, specify the new row size followed by column size.


.reshape has a special feature where it automatically detects the column number. This means that we do not actually have to specify a column number, we can simply just replace the column number with -1.

Exercises

Use this array for the following practice: 

myArray = np.array([[11,12,13], [14,15,16]])

Reshape the array to an array with 3 rows. Your results should look like this:

[[11 12]
 [13 14]
 [15 16]]