Articles → Numpy → Reshape Function In Numpy

Reshape Function In Numpy






Purpose





Syntax


array_object.reshape(dimensions)



Example


import numpy as np


# Create an array with 30 elements i.e. from 0 to 29
arr = np.arange(0,30)

# Printing array before reshaping.
print("Array before reshaping", arr)

# Change the space to 2D array using reshape function
# The number of elements in array before reshape i.e. 30 = multiplication of elements after reshape i.e. 6 * 5 
arr = arr.reshape(6,5)

# Finally printing the array after reshape
print("Array after reshaping", arr)




  1. An array ‘arr’ is created using arange function. In the array, we have 30 elements i.e. 0 to 29.
  2. Printing the array.
  3. Changing the size to a 2-dimensional array.
  4. Printing the array after reshape.




Picture showing the output of Reshape function in NumPy

Click to Enlarge


Find The Shape Of An Array Using Shape Attribute




import numpy as np


# Create an array with 30 elements i.e. from 0 to 29
arr = np.arange(0,30)

# Printing array before reshaping.
print("Shape of array before reshaping", arr.shape)

# Change the space to 2D array using reshape function
# The number of elements in array before reshape i.e. 30 = multiplication of elements after reshape i.e. 6 * 5 
arr = arr.reshape(6,5)

# Finally printing the array after reshape
print("Shape of array after reshaping", arr.shape)




Picture showing the output of Reshape function in NumPy

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 27, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250