In this example we will show how to reshape the NumPy array into any shape in Python.
Source Code
import numpy as np
n = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
# In both shapes, the elements required to reshape must be equal.
reshape_n_1 = n.reshape(3, 3)
print(reshape_n_1)
# The elements required to reshape are not equal, it will raise an error.
reshape_n_2 = n.reshape(3, 4)
print(reshape_n_2)
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
Traceback (most recent call last):
File "demo.py", line 10, in
reshape_n_2 = n.reshape(3, 4)
ValueError: cannot reshape array of size 9 into shape (3,4)