The shape of an array is simply the number of elements present in the array in any dimension.
Reshaping an array means changing the number of elements in each given dimension.
An array could by one dimensional 1D
, two dimensional 2D
, three dimensional 3D
, and so on. Changing an array, let’s say, from 1D
to 2D
is referred to as reshaping the array.
When reshaping an array, the new shape should be equal in length to the original shape. In other words, the elements required for reshaping must be equal in both shapes.
The array.reshape()
function reshapes an array in NumPy. This function gives a new shape to an array without changing its data.
array.reshape(shape)
The array.reshape()
method takes a tuple as its parameter value. The tuple represents the new shape to be created.
The array.reshape()
returns numpy.ndarray
.
1D
to 2D
We create a 1D
array with eight elements in the code below. We then reshape it to another equal shape but of a 2D
array with four arrays and two elements in each dimension.
import numpy as np# creating an arraymyarray = np.array([1, 2, 3, 4, 5, 6, 7, 8])# reshaping thenewarray = myarray.reshape(4, 2)print(newarray)
numpy
module1D
array, myarray
, with eight elementsarray.reshape()
function to reshape the existing array. We reshape it to an array with four arrays, each having two elements on them ( i.e., (4, 2)
). The output is assigned to a new array variable, newarray
.newarray
.1D
to 3D
In the example below, we reshape a 1D
array with 12 elements into a 3D
array with three arrays that contain two arrays with two elements each.
import numpy as np# creating a 1D arraymyarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])# reshaping the 1D array to a 3D array with has 3 arrays containing 2 arrays with 2 elements eachnewarray = myarray.reshape(3, 2, 2)print(newarray)
numpy
module.1D
array myarray
with 12 elements.array.reshape()
function to reshape the existing array. We change it to an array with three arrays containing two arrays with two elements each (i.e., (3, 2, 2)
). The output is assigned to a new array variable, newarray
.newarray
.