AppDividend
Latest Code Tutorials

np.reshape: How to Reshape Numpy Array in Python

Numpy reshape() can create multidimensional arrays and derive other mathematical statistics.  Numpy can be imported as import numpy as np. The np reshape() method is used for giving a new shape to an array without changing its elements.

np.reshape

The numpy.reshape(array, shape, order = ‘C’) function shapes an array without changing array data. The np.reshape() function accepts three arguments and returns the reshaped array.

To work with the np.reshape() function, you have to install numpy for this tutorial. To check your numpy version as well.

Let’s see the syntax of numpy reshape().

Syntax

numpy.reshape (a, newshape, order='C')

Parameters

1. array: This depicts the input_array whose shape is to be changed.
2. shape: This represents int value or tuples of int.
3. order: This parameter represents the order of operations. It can be either C_contiguous or F_contiguous, where C order operates row-rise on the array, and F order operates column-wise operations.

Return Value

The Numpy reshape() function returns an array with a new shape having its contents unchanged.

Examples

Program to show the working of the reshape() function.

import numpy as np

array = np.arange(6)
print("Array Value: \n", array)

# array reshaped with 3 rows and 2 columns
array = np.arange(6).reshape(3, 2)
print("Array reshaped with 3 rows and 2 columns : \n", array)

# array reshaped with 2 rows and 3 columns
array = np.arange(6).reshape(2, 3)
print("Array reshaped with 2 rows and 3 columns : \n", array)

Output

Array Value:
[0 1 2 3 4 5]
Array reshaped with 3 rows and 2 columns :
[[0 1]
[2 3]
[4 5]]
Array reshaped with 2 rows and 3 columns :
[[0 1 2]
[3 4 5]]

Explanation

In the above code original array was a 1D array.

So, in the 1st function, the array was modified to 3 rows and two columns.

In the 2nd function, the array was modified to 2 rows and three columns.

Note

In the above function, the array gets reshaped only when the size of the array is equal to the multiplication of rows and columns. If not, then the shell will prompt an error.

Example 2

See the following code.

import numpy as np

x = np.array([[21, 11, 19], [46, 18, 21]])
data = np.reshape(x, (2, -2))
print(data)

[[21 11 19]
[46 18 21]]

How to use ndarray.reshape() method in Python

Take the following one-dimensional NumPy array ndarray as an example.

# app.py

import numpy as np

arr = np.arange(12)
print('The array is:', arr)
print('The shape of array is:', arr.shape)
print('The dimension of array is:', arr.ndim)

Output

The array is: [ 0  1  2  3  4  5  6  7  8  9 10 11]
The shape of array is: (12,)
The dimension of array is: 1

Specify the converted shape as the list or tuple in the first argument of the reshape() method of numpy.ndarray.

See the following code.

import numpy as np

arr = np.arange(12)
print('The array is:', arr)
print('The shape of array is:', arr.shape)
print('The dimension of array is:', arr.ndim)

arr_3_4 = arr.reshape([3, 4])
print(arr_3_4)

print('The dimension is: ', arr_3_4.ndim)
print('The shape is: ', arr_3_4.shape)

Output

The array is: [ 0  1  2  3  4  5  6  7  8  9 10 11]
The shape of array is: (12,)
The dimension of array is: 1
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
The dimension is:  2
The shape is:  (3, 4)

First, we have defined an array then print the shape and dimension of the array.

Then, we have reshaped the array in the form of [3, 4] and then print the dimension and the shape of the array. If the shape does not match the number of items in the original array, then ValueError will be thrown.

Reshaping an array From 1D to 3D in Python

First, we will use the np arange() function to create a 1D array with.9 elements, and then we will use the reshape() method to reshape the array to a (3 x 3) array.

# importing the numpy module
import numpy as np

arr = np.arange(9)
print('1D Array using arange() method \n', arr)
print('\n')

print('3D Array using reshape() method')
data = arr.reshape(3, 3)
print(data)

Output

1D Array using arange() method
[0 1 2 3 4 5 6 7 8]

3D Array using reshape() method
[[0 1 2]
[3 4 5]
[6 7 8]]

You can see that we have created a 1D array using the arange() method and then reshaped that array into the 3D array using the reshape() method.

Can We Reshape an Array Into any Shape?

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

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

Let’s try converting a 1D array with 8 elements to a 2D array with 3 elements in each dimension.

# importing the numpy module
import numpy as np

arr = np.arange(8)

newarr = arr.reshape(3, 3)

print(newarr)

Output

Traceback (most recent call last):
File "app.py", line 6, in <module>
newarr = arr.reshape(3, 3)
ValueError: cannot reshape array of size 8 into shape (3,3)

We have got the ValueError: cannot reshape an array of size 8 into shape (3,3).

So, if you want to change the shape of an array, make sure that the dimension’s multiplication is equal to the length of the array.

Numpy reshape returns Copy or View?

Numpy reshape() method returns the original array, so it returns a view.

# importing the numpy module
import numpy as np

arr = np.arange(8)

print(arr.reshape(2, 4).base)

Output

[0 1 2 3 4 5 6 7]

You can see that it returns the original array. So it is a view.

Passing Unknown Dimension

In numpy reshape(), you are allowed to have one “unknown” dimension.

Meaning is 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.

# importing the numpy module
import numpy as np

arr = np.arange(8)

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

print(newarr)

Output

[[[0 1]
[2 3]]

[[4 5]
[6 7]]]

Please keep one thing in mind that we can not pass -1 to more than one dimension.

Flattening the arrays using numpy reshape()

A flattening array means converting a multidimensional array into a 1D array.

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

# importing the numpy module
import numpy as np

arr = np.array([[11, 21, 31], [46, 52, 62]])
print('The array is: \n', arr)
print('The dimension is: ', arr.ndim)

print('\n')

newarr = arr.reshape(-1)
print('After reshaping, The array is: \n', newarr)
print('After reshaping, the dimension is: ', newarr.ndim)

Output

The array is:
[[11 21 31]
[46 52 62]]
The dimension is:  2

After reshaping, The array is:
[11 21 31 46 52 62]
After reshaping, the dimension is:  1

You can see that, first, we have defined a 2D array and then flatten that 2D array to a 1D array using the reshape() method. We have printed its dimensions using the numpy ndim property.

Conclusion

In the numpy.reshape() function, specify an original numpy.ndarray as the first argument, and the shape to convert to the second argument as the list or tuple.

If the shape does not match the number of items in an original array, the ValueError will occur.