Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

NumPy Array Reshaping

Reshaping arrays

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.

Reshape From 1-D to 2-D

Example

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([123456789101112])

newarr = arr.reshape(43)

print(newarr)

Reshape From 1-D to 3-D

Example

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([123456789101112])

newarr = arr.reshape(232)

print(newarr)

Can We Reshape Into any Shape?

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.

Example

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([12345678])

newarr = arr.reshape(33)

print(newarr)