Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Numpy reshape() Function



The Numpy reshape() Function is used to change the shape of an array without altering its data. It returns a new view or array with the specified dimensions, provided the total number of elements remains constant.

This function takes two main arguments one is the array to reshape and the other is tuple specifying the new shape. If the new shape is not compatible with the total number of elements then a 'ValueError' is raised.

The Numpy reshape() Function is useful for transforming data to fit different processing requirements such as converting between row-major and column-major formats or preparing data for machine learning models.

Syntax

The syntax for the Numpy reshape() function is as follows −

numpy.reshape(arr, newshape, order='C')

Parameters

Following are the parameters of the Numpy reshape() Function −

  • arr: The input array that has to be reshaped.
  • newshape: This parameter can be int or tuple of int. New shape should be compatible to the original shape.
  • order: This parameter defines read and write order. If 'C' for row-major, 'F' for column-major.

Return Value

The reshape() function returns a new array with the same data but a different shape.

Example 1

Following is the basic example of Numpy reshape() Function. In this example we reshapes a 1D array of 8 elements into a 2x4 2D array −

import numpy as np

# Create a 1D array with 8 elements
a = np.arange(8)
print('The original array:')
print(a)
print('\n')

# Reshape the array to a 2D array with shape (4, 2)
b = a.reshape(4, 2)
print('The modified array:')
print(b)

Output

The original array:
[0 1 2 3 4 5 6 7]


The modified array:
[[0 1]
 [2 3]
 [4 5]
 [6 7]]

Example 2

Here this example uses -1 to automatically calculate the appropriate dimension for reshaping a 2x3 array into a 3x2 array −

import numpy as np

# Original array
a = np.array([[1, 2, 3], [4, 5, 6]])
# Reshaping the array to 3x2 using -1 to infer one of the dimensions
reshaped_array = np.reshape(a, (3, -1))

print("Original array:")
print(a)
print("Reshaped array (3x2):")
print(reshaped_array)

Output

Original array:
[[1 2 3]
 [4 5 6]]
Reshaped array (3x2):
[[1 2]
 [3 4]
 [5 6]]

Example 3

As we know that we can assign the order parameter based on our requirement so, in the below example we reshape a 2x3 array into a 3x2 array by defining order as 'F' i.e. Fortran-like column-major order −

import numpy as np

# Original array
a = np.array([[1, 2, 3], [4, 5, 6]])
# Reshaping the array to 3x2 in Fortran-like order
reshaped_array = np.reshape(a, (3, 2), order='F')

print("Original array:")
print(a)
print("Reshaped array (3x2) in Fortran-like order:")
print(reshaped_array)

Output

Original array:
[[1 2 3]
 [4 5 6]]
Reshaped array (3x2) in Fortran-like order:
[[1 5]
 [4 3]
 [2 6]]
numpy_array_manipulation.htm
Advertisements