๐ Introduction
While working with data, you often need to change the shape of arrays.
With NumPy, reshaping is simple and powerful.
๐ Why Reshaping is Important?
Reshaping helps you:
- Prepare data for machine learning
- Convert 1D to 2D arrays
- Adjust data structure
๐งช Example Array
import numpy as nparr = np.array([1, 2, 3, 4, 5, 6])
๐ 1. Reshape Array (reshape())
reshaped = arr.reshape(2, 3)
print(reshaped)
๐ Output:
[[1 2 3]
[4 5 6]]
โ Converts 1D โ 2D array
โ ๏ธ Important Rule
Total elements must match:
๐ 6 elements โ valid shapes:
- (2,3)
- (3,2)
๐ 2. Flatten Array (flatten())
arr2 = np.array([[1,2,3],[4,5,6]])flat = arr2.flatten()
print(flat)
๐ Output:
[1 2 3 4 5 6]
โ Returns a copy
๐ 3. Ravel Array (ravel())
r = arr2.ravel()
print(r)
๐ Output:
[1 2 3 4 5 6]
โ Returns a view (faster)
โ๏ธ Flatten vs Ravel
| Feature | flatten() | ravel() |
|---|---|---|
| Type | Copy | View |
| Speed | Slower | Faster |
| Memory | More | Less |
๐ 4. Reshape with -1
arr = np.array([1,2,3,4,5,6])print(arr.reshape(3, -1))
๐ Output:
[[1 2]
[3 4]
[5 6]]
โ NumPy automatically calculates dimension
โก Why Use NumPy?
Using NumPy:
- Makes reshaping easy
- Improves performance
- Handles large datasets
๐ฆ Real-World Use Case
# Prepare data for ML model
data = np.array([1,2,3,4,5,6])reshaped = data.reshape(3, 2)
print(reshaped)
โ Used in:
- Machine learning preprocessing
- Data transformation
๐ Works with Other Libraries
Reshaping is essential in:
- TensorFlow
- Scikit-learn
- Pandas
๐ Summary Table
| Function | Description |
|---|---|
| reshape() | Change shape |
| flatten() | Convert to 1D (copy) |
| ravel() | Convert to 1D (view) |
๐ง Pro Tips
- Use
-1for automatic dimension - Use
ravel()for performance - Use
flatten()when you need a copy
๐ Conclusion
Reshaping arrays in NumPy is essential for efficient data handling and transformation.