Open In App

numpy.reshape() in Python

Last Updated : 13 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

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)

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

Explanation:

  • array arr is reshaped into a 2×3 matrix, where 2 is number of rows and 3 is number of columns.
  • Each element from the original array is rearranged into the new shape while maintaining the order.

Syntax of numpy.reshape() :

numpy.reshape(array, shape, order = ‘C’)

Parameters : 

  • array : [array_like]Input array
  • shape : [int or tuples of int] e.g. The desired shape of the array. If one dimension is -1, the value is inferred from the length of the array and the remaining dimensions.
  • order : [C-contiguous, F-contiguous, A-contiguous; optional]
    • 'C' (default): Row-major order.
    • 'F': Column-major order.
    • 'A': Fortran-like index order if the array is Fortran-contiguous; otherwise, C-like order.
    • 'K': Keeps the array’s order as close to its original as possible.

Return Type: 

  • Array which is reshaped without changing the data.

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.

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:

  • -1 allows NumPy to automatically calculate the number of rows needed based on the total size and the other given dimension.
  • resulting array has 3 rows and 2 columns, as NumPy calculates the required number of rows.

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.

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)

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

Explanation:

  • order=’F’ argument reshapes the array in a column-major (Fortran-style) order, meaning the elements are filled by columns instead of rows.
  • The result is a 2×3 matrix where the data is arranged column-wise.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg