numpy.reshape() – The NumPy Reshape Python Function

Introduction to numpy.reshape() Function

The numpy.reshape() function shapes an array without changing its data.

Syntax:

numpy.reshape(array, shape, order = 'C')

Parameters:

  • array : [array_like]Input array
  • shape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then shaping it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)
  • order : [C-contiguous, F-contiguous, A-contiguous; optional]
    • C-contiguous order in memory(the last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker
    • FORTRAN-contiguous order in memory (the first index varies the fastest). F order means that column-wise operations will be faster.
    • A-contiguous ‘A’ means to read/write the elements in Fortran-like index order if, an array is Fortran contiguous in memory, C-like order otherwise

Return: Array which is reshaped without changing the data.

Code Examples of numpy.reshape() Function

Example 01:

# Welcome to softhunt.net
# Python Program illustrating
# numpy.reshape() method
 
import numpy as np
 
# array = np.arrange(8)
# The 'numpy' module has no attribute 'arrange'
array1 = np.arange(8)
print("Original array : \n", array1)
 
# shape array with 3 rows and 3 columns
array2 = np.arange(8).reshape(2, 4)
print("\narray reshaped with 2 rows and 4 columns : \n",
      array2)
 
# shape array with 4 rows and 2 columns
array3 = np.arange(8).reshape(4, 2)
print("\narray reshaped with 4 rows and 2 columns : \n",
      array3)
 
# Constructs 3D array
array4 = np.arange(8).reshape(2, 2, 2)
print("\nOriginal array reshaped to 3D : \n",
      array4)

Output:

NumPy Reshape

Explanation:

You will better understand if you look at the comments in the above code.

FAQs

What is reshape in NumPy?

Gives an array a new form without affecting its data. The array is going to be reconfigured. The new form should be compatible with the old one.

What is the use of reshape in Python?

In Python, we may reshape an array using the reshape() function. Changing the form of an array is referred to as reshaping. The number of items in each dimension determines the form of an array. We can reshape an array to add or remove dimensions.

What does it mean to reshape – 1?

The -1 in reshape(-1) in NumPy refers to an unknown dimension calculated by the reshape() function. It’s like saying, “I’ll let the reshape() function decide on this dimension.” Flattening a nested array with an unknown number of entries to a 1D array is a common use case.

Conclusion of numpy.reshape() Function

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. numpy.shape() – The NumPy Shape Python Function

Leave a Comment