numpy.reshape() in Python (original) (raw)

Last Updated : 13 Jan, 2025

In Python, **numpy.reshape() function is used to give a new shape to an existing NumPy array without changing its data. It is important for manipulating array structures in Python.

Let's understand with an example:

Python `

import numpy as np

Creating a 1D NumPy array

arr = np.array([1, 2, 3, 4, 5, 6])

Reshaping the 1D array into a 2D array with 2 rows and 3 columns

reshaped_arr = np.reshape(arr, (2, 3)) print(reshaped_arr)

`

**Explanation:

Table of Content

**Syntax of numpy.reshape() :

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

**Parameters :

**Return Type:

Using -1 to infer a dimension

It allows to automatically calculate the dimension that is unspecified as long as the total size of the array remains consistent.

Python `

import numpy as np

Creating a 1D NumPy array

arr = np.array([1, 2, 3, 4, 5, 6])

Reshaping the array into a 2D array

'-1' allows to calculate the number of rows based on the total number of elements

reshaped_arr = np.reshape(arr, (-1, 2))
print(reshaped_arr)

`

Output

[[1 2] [3 4] [5 6]]

**Explanation:

Reshaping with column-major order

We can specify the order in which the elements are read from the original array and placed into the new shape.

Python `

import numpy as np

Creating a 1D NumPy array

arr = np.array([1, 2, 3, 4, 5, 6])

Reshaping the array into a 2D array with 2 rows and 3 columns

reshaped_arr = np.reshape(arr, (2, 3), order='F') print(reshaped_arr)

`

**Explanation: