π 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.