In this tutorial, you’ll learn how to use NumPy reshape() to reshape NumPy arrays without changing the original data.

When working with Numpy arrays, you may often want to reshape an existing array into an array of different dimensions. This can be particularly useful when you transform data in multiple steps.

And NumPy reshape() helps you do it easily. Over the next few minutes, you’ll learn the syntax to use reshape(), and also reshape arrays to different dimensions.

What is Reshaping in NumPy Arrays?

When working with NumPy arrays, you may first want to create a 1-dimensional array of numbers. And then reshape it to an array with the desired dimension.

This is particularly helpful when the dimensions of the new array are not known initially or are inferred during execution. Or it may also be possible that a certain data processing step requires the input to be of a specific shape.

Here’s where reshaping comes in handy.

For example, consider the following illustration. We have a vector—a one-dimensional array of 6 elements. And we can reshape it into arrays of shapes 2×3, 3×2, 6×1, and so on.

NumPy reshape(): How to Reshape NumPy Arrays in Python Development Python

▶️ To follow along with the examples in this tutorial, you need to have Python and NumPy installed. If you don’t have NumPy yet, check out our NumPy installation guide.

You may now go ahead and import NumPy under the alias np, by running: import numpy as np.

Let’s proceed to learn the syntax in the next section.

Syntax of NumPy reshape()

Here’s the syntax to use NumPy reshape():

np.reshape(arr, newshape, order = 'C'|'F'|'A')
  • arr is any valid NumPy array object. Here, it’s the array to be reshaped.
  • newshape is the shape of the new array. It can be either an integer or a tuple.
  • When newshape is an integer, the returned array is one-dimensional.
  • order refers to the order in which you’d like to read in the elements of the array to be reshaped.
  • The default value is ‘C’, which means the elements of the original array will be read in a C-like indexing order (starting with 0)
  • ‘F’ stands for Fortran-like indexing (starting with 1). And ‘A’ reads in the elements in either C-like or Fortran-like order depending on the memory layout of the array arr.

So what does np.reshape() return?

It returns a reshaped view of the original array if possible. Else, it returns a copy of the array.

In the above line, we mentioned that NumPy reshape() would try to return a view whenever possible. Else, it returns a copy. Let’s proceed to discuss the differences between a view and a copy.

View vs. Copy of NumPy Arrays

As the name suggests, copy is a copy of the original array. And any changes made to the copy will not affect the original array.

On the other hand, view simply refers to reshaped view of the original array. This means that any change made to the view will also affect the original array and vice versa.

Use NumPy reshape() to Reshape 1D Array to 2D Arrays

#1. Let’s start by creating the sample array using np.arange().

We need an array of 12 numbers, from 1 to 12, called arr1. As the NumPy arange() function excludes the endpoint by default, set the stop value to 13.

Now let us use the above syntax, and reshape arr1 with 12 elements into a 2D array of shape (4,3). Let’s call this arr2 with 4 rows, and 3 columns.

import numpy as np

arr1 = np.arange(1,13)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr2 = np.reshape(arr1,(4,3))
print("nReshaped array:")
print(arr2)

Let’s take a look at the original and reshaped arrays.

Original array, before reshaping:

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

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

Instead of passing in the array as an argument np.reshape(), you can also call the .reshape() method on the original array.

You can run dir(arr1), and it will list down all the possible methods and attributes that you can use on the array object arr1.

dir(arr1)

# Output 
[
...
...
'reshape'
...
..
]

In the above code cell, you can see that .reshape() is a valid method to use on the existing NumPy array arr1.

▶️ So, you can also use the following simplified syntax to reshape NumPy arrays.

arr.reshape(d0,d1,...,dn)

# where:

# d0, d1,..,dn are the dimensions of the reshaped array

# d0 * d1 * ...* dn = N, the number of elements in arr

For the rest of this tutorial, let us use this syntax in our examples.

#2. Let’s try reshaping our 12-element vector into a 12 x 1 array.

import numpy as np

arr1 = np.arange(1,13)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr3 = arr1.reshape(12,1)
print("nReshaped array:")
print(arr3)

In the output below, you can see that the array has been reshaped as needed.

Original array, before reshaping:

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

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

❔ So, how do we check if we have obtained a copy or a view?

To check this, you can call the base attribute on the returned array.

  • If the array is a copy, the base attribute will be None.
  • If the array is a view, the base attribute will be the original array.

Let’s quickly verify this.

arr3.base
# Output
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

As you can see, base attribute of arr3 returns the original array. This means that we’ve received a view of the original array.

#3. Now, let’s try to reshape the vector into another valid 2 x 6 array.

import numpy as np

arr1 = np.arange(1,13)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr4 = arr1.reshape(2,6)
print("nReshaped array:")
print(arr4)

And here’s the output:

Original array, before reshaping:

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

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

In the next section, let’s reshape arr1 into a 3D array.

Use NumPy reshape() to Reshape 1D Array to 3D Arrays

To reshape arr1 to a 3D array, let us set the desired dimensions to (1, 4, 3).

import numpy as np

arr1 = np.arange(1,13)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr3D = arr1.reshape(1,4,3)
print("nReshaped array:")
print(arr3D)

We’ve now created a 3D array with the same 12 elements as the original array arr1.

Original array, before reshaping:

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

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

How to Debug Value Errors During Reshaping

If you remember the syntax, reshaping is valid only when the product of the dimensions is equal to the number of elements in the array.

import numpy as np

arr1 = np.arange(1,13)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr2D = arr1.reshape(4,4)
print("nReshaped array:")
print(arr2D)

Here, you’re trying to reshape a 12-element array into a 4×4 array with 16 elements. The interpreter throws a Value Error, as seen below.

Original array, before reshaping:

[ 1  2  3  4  5  6  7  8  9 10 11 12]
-----------------------------------------------------------
ValueError                                
Traceback (most recent call last)
 in ()
      6 
      7 # Reshape array
----> 8 arr2 = arr1.reshape(4,4)
      9 print("nReshaped array:")
     10 print(arr2)

ValueError: cannot reshape array of size 12 into shape (4,4)

To avoid such errors, you may use -1 to the automatically infer the shape for one of the dimensions—based on the total number of elements.

For example, if you know n – 1 dimensions beforehand, you can use -1 to infer the n-th dimension in the reshaped array.

If you have a 24-element array and you would like to reshape it into a 3D array. Suppose you need 3 rows and 4 columns. You can pass in the value of -1 along the third dimension.

import numpy as np

arr1 = np.arange(1,25)
print("Original array, before reshaping:n")
print(arr1)

# Reshape array
arr_res = arr1.reshape(4,3,-1)
print("nReshaped array:")
print(arr_res)
print(f"Shape of arr_res:{arr_res.shape}")

When you examine the shape of the shape array, you can see that the reshaped array has a shape of 2 along the third dimension.

Original array, before reshaping:

[ 1  2  3  4  5  6  7  8  9 10 11 12 
13 14 15 16 17 18 19 20 21 22 23 24]

Reshaped array:
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

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

 [[13 14]
  [15 16]
  [17 18]]

 [[19 20]
  [21 22]
  [23 24]]]
Shape of arr_res:(4, 3, 2)

This is particularly helpful in flattening an array. And you’ll learn about that in the next section.

Use NumPy reshape() to Flatten an Array

There are times when you’d need to go back from N-dimensional arrays to a flattened array. Suppose you want to flatten an image into a long vector of pixels.

Let’s code a simple example using the following steps:

  • Generate a 3 x 3 grayscale image array, img_arr—with pixels in the range 0 to 255.
  • Next, flatten this img_arr and print out the flattened array, flat_arr.
  • Also, print out the shapes of img_arr and flat_arr to verify.
img_arr = np.random.randint(0, 255, (3,3))
print(img_arr)
print(f"Shape of img_arr: {img_arr.shape}")
flat_arr = img_arr.reshape(-1)
print(flat_arr)
print(f"Shape of flat_arr: {flat_arr.shape}")

Here’s the output.

[[195 145  77]
 [ 63 193 223]
 [215  43  36]]
Shape of img_arr: (3, 3)

[195 145  77  63 193 223 215  43  36]
Shape of flat_arr: (9,)

In the above code cell, you can see that flat_arr is a 1D vector of pixel values with 9 elements.

Summing Up👩‍🏫

It’s time to quickly review what we have learned.

  • Use np.reshape(arr, newshape) to reshape arr into the shape specified in newshape. newshape is a tuple specifying the dimensions of the reshaped array.
  • Alternatively, use arr.reshape(d0, d1, …, dn) to reshape arr to be of shape d0 x d1 x … x dn
  • Check if d0 * d1 * …* dn = N, the number of elements in the original array, to avoid Value Errors during reshaping.
  • Use -1 for at most one dimension in the new shape if you would like the dimension to be automatically inferred.
  • Finally, you may use arr.reshape(-1) to flatten the array.

Now that you know how to use NumPy reshape(), learn how the NumPy linspace() function works.

You may try out the code examples in Jupyter notebook if you’d like. If you’re looking for other development environments, check out our guide on Jupyer alternatives.