Numpy reshape() - function for reshaping arrays
In 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
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 parameters
Here 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.
Return value: An array which is reshaped without any change to its data.
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)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] (20,) 1
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.
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]))
[[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]]]
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)
We can reshape any array into any shape as long as the elements required for reshaping are equal in both shapes. Interestingly, we are allowed to have one “unknown” dimension. What that means is that you don’t have to specify an example number for one of the dimensions in the reshape method. In such a case, pass -1 as the value (Eg: y = arr.reshape(2, 2, -1)) and NumPy will calculate this number for you.