📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials NumPy Array Reshaping

Array Reshaping

5 min read Quiz at the end
Reshape, flatten, transpose, and add/remove dimensions to transform array structure.

Reshaping Arrays

import numpy as np
a = np.arange(12)   # [0 1 2 ... 11]

a.reshape(3, 4)     # 3x4 array
a.reshape(2, 6)     # 2x6 array
a.reshape(2, 2, 3)  # 3D: 2x2x3
a.reshape(-1, 4)    # -1 = infer from other dims

# Flatten
b = np.array([[1,2],[3,4]])
b.flatten()         # [1 2 3 4] — copy
b.ravel()           # [1 2 3 4] — view (faster)

# Transpose
b.T                 # swap rows and cols
np.transpose(b)     # same

# Add/remove dimensions
a[np.newaxis, :]    # shape (1, 12)
a[:, np.newaxis]    # shape (12, 1)
np.expand_dims(a, 0)
np.squeeze(a)       # remove size-1 dimensions
Topic Quiz · 1 questions

Test your understanding before moving on

1. What does array.reshape(-1, 4) do?
💡 The -1 tells NumPy to infer the dimension size from the total element count and the given 4.