Numpy reshape() - function for reshaping arraysIn this quick tutorial we are going to learn how to reshape an array using the numpy.reshape() function.
Table of Contents - Numpy reshape
- What is reshaping in Python?
- Syntax and parameters
- How to use the numpy.reshape() method in Python?
- Closing thoughts
- Other Related Concepts
What is reshaping in Python?The numpy.reshape() function allows us to reshape an array in Python. Reshaping basically means, changing the shape of an array. And the shape of an array is determined by the number of elements in each dimension.
Reshaping allows us to add or remove dimensions in an array. We can also change the number of elements in each dimension.
Syntax and parametersHere is the syntax of the function:
numpy.reshape(array, shape, order = 'C')
- array: Input array.
- shape: Integers or tuples of integers.
- order: C-contiguous, F-contiguous, A-contiguous; this is an optional parameter. ‘C’ order means that operating row-rise on the array will be slightly quicker. ‘F’ order means that column-wise operations will be faster. ‘A’ means to read / write the elements in Fortran-like index order.
How to use the numpy.reshape() method in Python?Let’s take the following one-dimensional NumPy array as an example.
import numpy as np x = np.arange(20) #prints out the array with its elements print(x) print() #prints out the shape of the array print(x.shape) print() #prints out the dimension value of the array print(x.ndim)
In this case, the numbers [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] are the elements of the array x. The output (20,)is the shape of the array. Finally the value 1 printed out signifies the dimension of the array.
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] (20,) 1
Now to try out the numpy reshape function, we need to specify the original array as the first argument and the shape of the second argument as a list or tuple. However, do keep in mind that if the shape does not match the number of elements in the original array, a ValueError will occur.
In the example below, we are converting the defined 1-D array with 20 elements into a 2-D array. The outermost dimension will have 2 arrays that contain 2 arrays, each with 5 elements.
print(np.reshape(x, [2, 2, 5]))
So an attempt like print(np.reshape(x, [5,6])) will run into a ValueError. This is because we cannot reshape an array of size 20 into shape (5,6)
[[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]]]