NumPy Array Reshaping
✅ 1. Using reshape()
You can convert a 1D array into 2D, 3D, etc.
Example: Convert 1D → 2D
Output:
✅ 2. Reshape to 3 Dimensions
Output:
⚠️ Important Rule: Total Elements Must Match
If the total number of items doesn’t match, reshape will give an error.
❌ Error (because 3 elements cannot be reshaped into a 4-element structure).
✅ 3. Using -1 (Auto Calculate Dimension)
NumPy can automatically calculate missing dimension using -1.
Example:
Output:
✅ 4. Flatten an Array (reshape(-1))
Convert multi-dimensional array back to 1D.
Output:
✅ 5. Check If Reshape Returns a View or Copy
If output is True, reshaping created a view, not a new copy.
Summary Table
| Operation | Function | Changes Data? | Changes Shape? |
|---|---|---|---|
| Flatten array | .reshape(-1) |
❌ No | ✔ Yes |
| 1D → 2D | .reshape(r, c) |
❌ No | ✔ Yes |
| Auto dimension | .reshape(-1) |
❌ No | ✔ Yes |
| View or Copy? | .reshape() |
Sometimes | ✔ Yes |
🎯 Practical Example
Output:
