Table of Contents
ToggleBy 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 2×2 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,
In the following example, we are reshaping a 1D array “arr” with “6” elements into a 2D array using the reshape() function −
# Open Compiler
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)
Output:
Following is the output obtained −
1-D to 2-D Array (2×3):
[[1 2 3]
[4 5 6]]
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 −
# Open Compiler
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)
Output:
This will produce the following result −
Scores Matrix (2 students, 3 tests each):
[[85 90 78]
[92 88 76]]
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.
In this example, we are reshaping a 1-D array “arr” with “12” elements into a 3-D array using the reshape() function −
# Open Compiler
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)
Output:
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 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 makes the data easier to handle and analyze.
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 −
# Open Compiler
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)
Output:
The output obtained is as shown below −
Reshaped Array: [1 2 3 4 5 6]
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.
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” −
# Open Compiler
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)
Output:
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]]]
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.
Following are the most common errors that occur while reshaping an array in NumPy −
reshape((3, 3))) will raise this error because 3 × 3 = 9 which is different from 10.reshape((2, 5))) will raise this error because 2 × 5 = 10, but the array needs to be 2-dimensional to fit the new shape.reshape() function are valid integers and that they correctly represent the new shape.Following are the ways to handle errors that occur while reshaping an array in NumPy −
array.size() function and ensure it matches the product of the new shape dimensions.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.In the following example, we attempt to reshape a 1D array “arr” with 5 elements into a “2×3” 2D array, which results in a ValueError because the total number of elements does not match the specified shape −
# Open Compiler
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)
Output:
The error obtained is as follows −
Error Occurred During Reshaping:
cannot reshape array of size 5 into shape (2,3)
Key Takeaway: Learn to reshape NumPy arrays effectively at Vista Academy!
