NUMPY Tutorial



NumPy ARRAY RESHAPE


🔹 NumPy Array Reshape

The reshape() method in NumPy lets you change the shape (dimensions) of an existing array without changing its data.

✅ Why Reshape?

  • Adjust data to fit matrix operations.
  • Prepare arrays for algorithms requiring specific dimensions.
  • Organize data for visualization or further processing.

🎯 Basic Syntax

new_array = original_array.reshape(new_shape)

new_shape is a tuple specifying the desired shape (dimensions).

🧰 Important Rules

  • The total number of elements must remain the same before and after reshaping.
  • Shape tuple can include -1 for one dimension, letting NumPy automatically calculate it.

✅ Examples

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)

🔀 Using -1 to Automatically Infer Dimension

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)

⚠️ Common Errors

  • ValueError: cannot reshape array of size X into shape (a, b, ...) — means total elements mismatch.
  • Make sure new_shape product equals the number of elements.

🔎 Summary

  • reshape() returns a new view or copy with changed shape.
  • The original array remains unchanged unless reassigned.
  • Useful for data manipulation and preparing input for ML and scientific computing.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review