🔄 Array Manipulation
Array manipulation lets you transform data structure and organization efficiently! Whether reshaping for machine learning, splitting for processing, or joining datasets, these are essential skills for data handling.
import numpy as np
# Array manipulation basics
data = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
print(f"Original: \n{data}")
# Reshape to different dimensions
reshaped = data.reshape(4, 2)
print(f"Reshaped: \n{reshaped}")
# Split into parts
parts = np.hsplit(data, 2)
print(f"Split: {parts[0]} and {parts[1]}")
🎯 Why Array Manipulation Matters
Array manipulation enables:
- Data preparation: Reshape for algorithms
- Memory optimization: Views vs copies
- Data organization: Split into chunks
- Data combination: Join multiple sources
🔧 Quick Examples
Reshaping Data
import numpy as np
# Time series data - daily sales for 4 weeks
daily_sales = np.array([100, 120, 110, 95, 105, 130, 125,
115, 140, 135, 90, 100, 145, 150])
# Reshape to weekly view
weekly = daily_sales.reshape(2, 7)
print(f"Weekly sales: \n{weekly}")
print(f"Week averages: {weekly.mean(axis=1)}")
Splitting Arrays
import numpy as np
# Split dataset for train/test
data = np.random.rand(100, 5)
train, test = np.split(data, [80])
print(f"Training set: {train.shape}")
print(f"Test set: {test.shape}")
Joining Arrays
import numpy as np
# Combine results from different sources
results_a = np.array([85, 90, 88])
results_b = np.array([82, 87, 91])
combined = np.vstack([results_a, results_b])
print(f"Combined results: \n{combined}")
print(f"Overall average: {combined.mean():.1f}")
💡 Views vs Copies
Understanding memory behavior is crucial:
import numpy as np
original = np.array([1, 2, 3, 4, 5])
# View (shares memory)
view = original[1:4]
print(f"View shares memory: {np.shares_memory(original, view)}")
# Copy (independent)
copy = original.copy()
print(f"Copy shares memory: {np.shares_memory(original, copy)}")
# Modify view affects original
view[0] = 999
print(f"Original after view change: {original}")
📚 What You'll Learn
This section covers essential manipulation techniques:
- 🔄 Reshaping Arrays - Change dimensions and structure
- ✂️ Splitting and Joining Arrays - Divide and combine arrays
- 🎭 Copying and Views - Memory management essentials
🎯 Key Takeaways
🚀 What's Next?
Ready to master array manipulation? Start with reshaping - the fundamental skill for organizing your data.
Continue to: Reshaping Arrays
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.