/Curriculum/Core NumPyArray Transformation

11. NumPy Shape & ReshapingBeginner

Transform dimensions using reshape(), flatten(), ravel(), and transpose (.T).

14 mins

Concept Overview

Reshaping changes the dimensional arrangement of an array without altering its underlying data. The total element count must remain unchanged.

Hardware Mental Model

Reshaping a 1D strip of 6 numbers into a 2x3 grid is like folding a strip of 6 stamps into 2 rows of 3 stamps without ripping any stamps.

Key Concepts (1)Click snippet to load in editor

Pass `-1` as one dimension in `.reshape(r, -1)` and NumPy will automatically compute the required dimension size.

mat = arr.reshape(2, 3); flat = mat.flatten()

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:arr = np.arange(6); arr.reshape(2, 4) # 2x4 = 8 != 6
✓ Correct:arr = np.arange(6); arr.reshape(2, 3)

The product of the new shape dimensions must exactly equal the total number of elements.

Pro Tip: Use `reshape(rows, -1)` to let NumPy calculate the matching column count automatically.

📌 Quick Revision

Core takeaway points from this topic
`arr.reshape(r, c)`: Reorganizes dimensions without modifying data.
`arr.T` / `arr.transpose()`: Swaps rows and columns.
`arr.flatten()`: Returns a flattened 1D copy.
`arr.ravel()`: Returns a flattened 1D view.
Editor: 11. NumPy Shape & Reshaping
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Reshape 1D to 2x2 Matrix

Create `arr = np.array([10, 20, 30, 40])`, reshape it into a 2x2 matrix using `.reshape(2, 2)`, and print it.

Expected Output Target:[[10 20] [30 40]]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state