🔄 Reshaping Arrays

Reshaping changes array dimensions while keeping all data intact. Essential for organizing data for different algorithms and analysis.

import numpy as np

# Basic reshaping
data = np.arange(12)
print(f"Original: {data}")

# Reshape to 2D
matrix = data.reshape(3, 4)
print(f"3x4 matrix: \n{matrix}")

📐 Basic Operations

Change Dimensions

import numpy as np

data = np.arange(24)

# Different shapes (total elements must stay same)
print(f"2x12: \n{data.reshape(2, 12)}")
print(f"4x6: \n{data.reshape(4, 6)}")

Auto-Calculate Size

import numpy as np

data = np.arange(20)

# Use -1 to auto-calculate dimension
print(f"Auto rows: \n{data.reshape(-1, 4)}")  # 5x4
print(f"Auto cols: \n{data.reshape(5, -1)}")  # 5x4

🔄 Flattening Arrays

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])

# Convert to 1D
flattened = matrix.flatten()
raveled = matrix.ravel()

print(f"Original: \n{matrix}")
print(f"Flattened: {flattened}")

🔀 Transposing

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])

print(f"Original: \n{matrix}")
print(f"Transposed: \n{matrix.T}")

🎯 Practical Uses

Time Series Organization

import numpy as np

# 28 days of sales
daily_sales = np.random.randint(100, 300, 28)

# Organize by weeks
weekly = daily_sales.reshape(4, 7)
print(f"Week 1 total: {weekly[0].sum()}")

Machine Learning Data

import numpy as np

# Image to ML format
image = np.random.randint(0, 256, (28, 28))
ml_input = image.reshape(-1)  # Flatten to 1D

print(f"Image shape: {image.shape}")
print(f"ML input shape: {ml_input.shape}")

🎯 Key Takeaways

🚀 What's Next?

Learn to split and join arrays for data organization.

Continue to: Splitting and Joining Arrays

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent