Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: NP.5 Array Reshaping

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of 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]]