Table Of Contents
- Shape-Shifting Arrays Without Breaking a Sweat
- Reshaping in Action
- Reshape Rules and Tricks
- Common Patterns
- Performance Tips
- Next Level NumPy
Shape-Shifting Arrays Without Breaking a Sweat
Ever had a flat array that needs to become a matrix? Or a 3D tensor that should be 2D? NumPy's reshape() is your dimensional Swiss Army knife.
Reshaping in Action
import numpy as np
# Basic reshaping
flat = np.array([1, 2, 3, 4, 5, 6])
matrix = flat.reshape(2, 3)
print(matrix)
# [[1 2 3]
# [4 5 6]]
# Use -1 to infer dimension
auto_shape = flat.reshape(-1, 2)
print(auto_shape)
# [[1 2]
# [3 4]
# [5 6]]
# 3D reshaping
tensor = np.arange(24).reshape(2, 3, 4)
print(tensor.shape) # (2, 3, 4)
# Flatten back to 1D
flattened = tensor.reshape(-1)
print(flattened.shape) # (24,)
# Order matters: C vs Fortran
arr = np.arange(6).reshape(2, 3)
print(arr.reshape(3, 2, order='C')) # Row-major (default)
print(arr.reshape(3, 2, order='F')) # Column-major
# View vs Copy
original = np.array([1, 2, 3, 4])
view = original.reshape(2, 2)
view[0, 0] = 99
print(original) # [99 2 3 4] - Original changed!
Reshape Rules and Tricks
- Size must match: Total elements must remain the same
- Use -1 wisely: Let NumPy calculate one dimension
- Views when possible: Reshape usually returns a view, not a copy
- Contiguous memory: Some reshapes require copying data
Common Patterns
# Image data: (height, width, channels) to (pixels, channels)
image = np.random.rand(28, 28, 3)
pixels = image.reshape(-1, 3)
# Batch processing
data = np.arange(100)
batches = data.reshape(10, 10) # 10 batches of 10
Performance Tips
- Reshape returns a view when possible (no data copying)
- Use
ravel()
for guaranteed view when flattening flatten()
always returns a copy
Next Level NumPy
Explore NumPy broadcasting magic, master advanced array indexing, and dive into NumPy's performance tricks.
Share this article
Add Comment
No comments yet. Be the first to comment!