Reshaping is the process of changing the shape of an array, which defines the number of elements in each dimension. This allows us to add or remove dimensions or modify the number of elements within existing dimensions.
Transform the following 1-D array with 12 elements into a 2-D array, where the outermost dimension consists of 4 arrays, each containing 3 elements.
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) newarr = arr.reshape(4, 3) print(newarr) |
Convert the following 1-D array with 12 elements into a 3-D array, where the outermost dimension contains 2 arrays, each consisting of 3 arrays with 2 elements each.
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) newarr = arr.reshape(2, 3, 2) print(newarr) |
Yes, reshaping is possible if the total number of elements matches. For instance, we can reshape an 8-element 1-D array into a 2-D array with 4 elements in 2 rows, but not into a 3-D array with 3 elements in 3 rows, as that would require 9 elements.
Attempt to convert a 1-D array with 8 elements into a 2-D array with 3 elements in each dimension (this will raise an error).
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) newarr = arr.reshape(3, 3) print(newarr) |