NumPy - Reshaping Arrays

Reshaping NumPy Array

By reshaping a NumPy array, we mean to change its shape, i.e., modifying the number of elements along each dimension while keeping the total number of elements the same. In other words, the product of the dimensions in the new shape must equal the product of the dimensions in the original shape.

For instance, an array of shape (6,) can be reshaped to (2, 3) or (3, 2), but not to (2, 2) since 6 elements cannot fit into a 2x2 array.

Reshaping 1D Array to 2D Array

We can reshape a 1-D array to a 2-D array in NumPy using the reshape() function. This is used to organize linear data into a matrix form.

The reshape() function changes the shape of an existing array without changing its data. Following is the syntax −

numpy.reshape(array, newshape)

Where,

  • array − The array you want to reshape.
  • newshape − The shape you want to give the array. It can be an integer or a tuple of integers. One dimension can be -1, which means it will be presumed from the length of the array and the remaining dimensions.

Example: Basic Reshaping

In the following example, we are reshaping a 1D array “arr” with “6” elements into a 2D array using the reshape() function −

import numpy as np

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

# Reshape to 2-D array 
reshaped_arr = arr.reshape((2, 3))
print("1-D to 2-D Array (2x3):")
print(reshaped_arr)

Following is the output obtained −

1-D to 2-D Array (2x3):
[[1 2 3]
 [4 5 6]]

Example: Practical Use Case of Reshaping

Imagine you have a list of test scores for students in a class, and you want to organize them into a table where each row represents a student, and each column represents a different test. You can do this by reshaping the 1D array of scores into a 2D array −

import numpy as np
# Original 1-D array of test scores
scores = np.array([85, 90, 78, 92, 88, 76])

# Reshape into a 2-D array where each row is a student's scores
scores_matrix = scores.reshape((2, 3))
print("Scores Matrix (2 students, 3 tests each):")
print(scores_matrix)

This will produce the following result −

Scores Matrix (2 students, 3 tests each):
[[85 90 78]
 [92 88 76]]

Reshaping 1D Array to 3D Array

We can also reshape a 1-D array to a 3-D array in NumPy using the reshape() function. This helps you to represent data with more complex structures such as multi-channel images (e.g., RGB images), time-series data across different channels, or volumetric data.

Example

In this example, we are reshaping a 1-D array “arr” with “12” elements into a 3-D array using the reshape() function −

import numpy as np

# Original 1-D array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# Reshape to 3-D array
reshaped_arr = arr.reshape((2, 2, 3))
print("1-D to 3-D Array (2x2x3):")
print(reshaped_arr)

Following is the output of the above code −

1-D to 3-D Array (2x2x3):
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]

Reshaping ND Array to 1D Array

Reshaping an N-Dimensional (N-D) array to a 1-Dimensional (1-D) array in NumPy is a process of flattening or collapsing the multi-dimensional array into a single linear array. We can achieve this as well using the reshape() function.

Flattening complex multi-dimensional arrays into a 1-D format simplifies certain data processing tasks and make the data easier to handle and analyse.

Example

In the example below, we are reshaping a 2-D array “arr” with shape (2, 3) into a 1-D array using the reshape() function with -1 as the argument −

import numpy as np

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

# Reshape to 1-D array
reshaped_arr = arr.reshape(-1)
print("Reshaped Array:", reshaped_arr)

The output obtained is as shown below −

Reshaped Array:[1 2 3 4 5 6]

Reshaping Unknown Dimension Arrays

You can reshape an array with an unknown dimension using the reshape() function in NumPy. By passing -1 as an argument to reshape() function, NumPy automatically calculates the size of that dimension based on the total number of elements in the array and the other specified dimensions.

This helps you to reshape arrays without explicitly computing the exact size of every dimension.

Example

In the following example, we are reshaping a 1-D array arr with “12” elements into a “3-D” array using the reshape() function, specifying one of the dimensions as “-1” −

import numpy as np

# Original 1-D array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# Reshape to 3-D array with one unknown dimension
reshaped_arr = arr.reshape((2, 2, -1))
print("Reshaped Array with Unknown Dimension:")
print(reshaped_arr)

After executing the above code, we get the following output −

Reshaped Array with Unknown Dimension:
[[[ 1  2  3]
  [ 4  5  6]][[ 7  8  9]
  [10 11 12]]]

Error Occurrence while Reshaping Array

Reshaping arrays in NumPy can sometimes lead to errors, especially when the total number of elements does not match the product of the specified dimensions. It is important to ensure that the new shape is compatible with the number of elements in the array.

Common Errors while Reshaping Array

Following are the most common errors that occur while reshaping an array in NumPy −

  • ValueError: Total size of new array must be unchanged − This error occurs when the number of elements in the original array does not match the product of the dimensions specified for reshaping.

    For example, trying to reshape a 1-D array of 10 elements into a 3x3 matrix (reshape((3, 3))) will raise this error because 3 × 3 = 9 which is different from 10.

  • ValueError: cannot reshape array of size X into shape (Y, Z) − This error indicates that the original array size (X) is not compatible with the specified shape (Y, Z).

    For instance, trying to reshape a 1-D array of size 10 into a 2x5 matrix (reshape((2, 5))) will raise this error because 2 × 5 = 10, but the array needs to be 2-dimensional to fit the new shape.

  • TypeError: ‘numpy.ndarray’ object cannot be interpreted as an integer − This error occurs when the dimensions provided for reshaping are not integers or are incorrectly specified. Ensure that all dimensions passed to reshape() function are valid integers and that they correctly represent the new shape.

Handling Errors while Reshaping Array

Following are the ways to handle errors that occur while reshaping an array in NumPy −

  • Check Array Size Before reshaping, verify the size of your original array using array.size() function and ensure it matches the product of the new shape dimensions.
  • Use -1 for Unknown Dimensions When reshaping, if one dimension is unknown, use -1 to let NumPy calculate it automatically based on the total number of elements in the array.
  • Catch Exceptions Wrap your reshaping code in a try-except block to catch potential errors and handle them gracefully. This can prevent your program from crashing and allow for appropriate error messaging or fallback actions.

Example

In the following example, we attempt to reshape a 1D array “arr” with 5 elements into a “2x3” 2D array, which results in a ValueError because the total number of elements does not match the specified shape −

import numpy as np

# Original 1-D array
arr = np.array([1, 2, 3, 4, 5])

try:
   # Attempt to reshape to an incompatible shape
   reshaped_arr = arr.reshape((2, 3))
except ValueError as e:
   print("Error Occurred During Reshaping:")
   print(e)

The error obtained is as follows −

Error Occurred During Reshaping:
cannot reshape array of size 5 into shape (2,3)
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team