The reshape()
method in NumPy lets you change the shape (dimensions) of an existing array without changing its data.
new_array = original_array.reshape(new_shape)
new_shape
is a tuple specifying the desired shape (dimensions).
-1
for one dimension, letting NumPy automatically calculate it.import numpy as np
# Create a 1D array of 12 elements
arr = np.arange(12)
print("Original array:")
print(arr)
print("Shape:", arr.shape) # (12,)
# Reshape to 2D array with 3 rows, 4 columns
arr_reshaped = arr.reshape(3, 4)
print("\nReshaped to (3, 4):")
print(arr_reshaped)
print("Shape:", arr_reshaped.shape) # (3, 4)
# Reshape to 3D array
arr_3d = arr.reshape(2, 2, 3)
print("\nReshaped to (2, 2, 3):")
print(arr_3d)
print("Shape:", arr_3d.shape) # (2, 2, 3)
arr = np.arange(8)
print("Original shape:", arr.shape) # (8,)
# Automatically calculate columns
reshaped = arr.reshape(2, -1)
print("Reshaped with -1:")
print(reshaped)
print("Shape:", reshaped.shape) # (2, 4)
ValueError: cannot reshape array of size X into shape (a, b, ...)
— means total elements mismatch.new_shape
product equals the number of elements.reshape()
returns a new view or copy with changed shape.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!