AtomLearn
DashboardGoalsGraphAchievementsReviewSign In
DashboardNumPyArray Shape & Reshape
NumPyNot Started

Array Shape & Reshape

Understanding and changing the dimensions of an array

0%

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

Shape describes an array's dimensions. A 1D array of 12 elements has shape (12,). That same data as a 3×4 matrix has shape (3, 4).

reshape() changes shape without changing data: ``python a = np.arange(12) # shape (12,) b = a.reshape(3, 4) # shape (3, 4) c = a.reshape(2, 2, 3) # shape (2, 2, 3) — 3D

Rules:

- Total elements must stay the same: 12 = 3×4 = 2×2×3 ✓ - Use -1 to let NumPy infer one dimension: ``python a.reshape(-1, 4) # NumPy figures out rows = 3 a.reshape(3, -1) # NumPy figures out cols = 4

flatten() vs ravel():

  • flatten() — returns a copy as 1D
  • ravel() — returns a view (faster, no copy)

Why this matters: ML models often require inputs in specific shapes. Flattening images (28×28 → 784) before feeding to a neural network is a common operation.

Examples

Reshape in practice

-1 as a dimension means "figure it out"

import numpy as np

a = np.arange(12)
print(a.shape)          # (12,)

b = a.reshape(3, 4)
print(b.shape)          # (3, 4)

c = a.reshape(-1, 6)    # NumPy infers 2 rows
print(c.shape)          # (2, 6)

print(b.flatten().shape)  # (12,)

Next in NumPy

Array Indexing

Continue