numpy.reshape() in Python


By using numpy.reshape() function we can give new shape to the array without changing data. Sometimes we need to change only the shape of the array without changing data at that time reshape() function is very much useful.

Basic Syntax

numpy.reshape() in Python function overview
numpy.reshape() in Python function overview

Following is the basic syntax for Numpy reshape() function:

numpy.reshape(arr, new_shape, order)

And the parameters are:

Parameter Description
arr array which should be reshaped
new_shape new shape for array which should be compatible with original shape, int or tuple of int.
order ‘C’ for C style, ‘F’ for F style (Fortran Style) , ‘A’ for Fortran like order if the array is stored in Fortran like contiguous memory else C style

Returns

This function returns reshaped array

Example

Below is an example for Numpy reshape() function:

# Python Program for numpy.reshape() function
  
import numpy as np 
  
array = np.arange(12);
print("Original array : \n", array) 
  
# shape array with 2 rows and 4 columns 
array = np.arange(12).reshape(2, 6) 
print("\nReshaped array with 2 rows and 6 columns : \n", array) 
  
# shape array with 2 rows and 4 columns 
array = np.arange(12).reshape(4 ,3) 
print("\nReshaped array with 4 rows and 3columns : \n", array) 

# shape array with 2 rows and 4 columns 
array = np.arange(12).reshape(3 ,4) 
print("\nReshaped array with 3 rows and 4 columns : \n", array) 
  
# Constructs 3D array 
array = np.arange(12).reshape(2, 3, 2) 
print("\nOriginal array reshaped to 3D view : \n", array) 

The output should be:

Original array :
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Reshaped array with 2 rows and 6 columns :
[[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]]
Reshaped array with 4 rows and 3columns :
[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]]
Reshaped array with 3 rows and 4 columns :
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]
Original array reshaped to 3D view :
[[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]]