It is used to reshape Numpy array without modifying the original array. This function returns a new array with the specified shape. You can use reshape()
function in two ways-
numpy.reshape(array, newshape)
array
parameter refers to the array that you want to reshape.
newshape
parameter is used to specify the new shape. You provide either integer value or a tuple. When you specify newshape in the form of tuple like this (x, y)
then x
represents rows and y
represents columns.
Let's understand it with the help of an example-
import numpy as np a = np.array([[5, 6, 7], [8, 9, 10]]) #Two different ways of passing newshape value to numpy.reshape() function print(np.reshape(a, 6))#Convert 2-D array to 1-D array print(np.reshape(a, (3, 2)))#Modifying array a to another 2-D array having 3 rows and 2 columns print('Original array: \n', a)
Output of the above program
[ 5 6 7 8 9 10] [[ 5 6] [ 7 8] [ 9 10]] Original array: [[ 5 6 7] [ 8 9 10]]
numpy.ndarray.reshape(newshape)
newshape
parameter is used to provide the new shape. You provide integer value, a tuple or comma-separated values.
Let's understand reshape() function that is applied on Numpy array using an example-
import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) #Three different ways of passing newshape value to numpy.ndarray.reshape() function print(a.reshape(8)) #Convert 2-D array to 1-D array print(a.reshape(4, 2))#Modifying array a to another 2-D array having 4 rows and 2 columns print(a.reshape((4, 2)))#Modifying array a to another 2-D array having 4 rows and 2 columns print('Original array: \n', a)
Output of the above program
[1 2 3 4 5 6 7 8] [[1 2] [3 4] [5 6] [7 8]] [[1 2] [3 4] [5 6] [7 8]] Original array: [[1 2 3 4] [5 6 7 8]]