Shape Manipulation & Reshape
Understanding shape
Section titled “Understanding shape”shape tells the size of each dimension.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3)Reshape with .reshape()
Section titled “Reshape with .reshape()”Reshape changes the dimension layout without changing the underlying data or copying it — it just reinterprets the same flat block of memory with a new shape.
import numpy as np
arr = np.arange(1, 13) # 1..12
mat = arr.reshape(3, 4) # 3 rows, 4 cols
print(mat)Using -1 (auto infer)
Section titled “Using -1 (auto infer)”import numpy as np
arr = np.arange(12)
mat = arr.reshape(3, -1)
print(mat.shape) # (3, 4)Flattening arrays
Section titled “Flattening arrays”.ravel() (often a view)
Section titled “.ravel() (often a view)”import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.ravel()
print(flat).flatten() (always copy)
Section titled “.flatten() (always copy)”import numpy as np
mat = np.array([[1, 2], [3, 4]])
flat = mat.flatten()
print(flat)Add or remove dimensions
Section titled “Add or remove dimensions”np.newaxis / None
Section titled “np.newaxis / None”Convert a 1D array into a column vector:
import numpy as np
arr = np.array([1, 2, 3])
col = arr[:, None]
print(col)
print(col.shape) # (3, 1)np.expand_dims
Section titled “np.expand_dims”import numpy as np
arr = np.array([1, 2, 3])
arr2 = np.expand_dims(arr, axis=0)
print(arr2.shape) # (1, 3)np.squeeze (remove size-1 dims)
Section titled “np.squeeze (remove size-1 dims)”import numpy as np
arr = np.array([[[1], [2], [3]]])
print(arr.shape) # (1, 3, 1)
print(np.squeeze(arr).shape) # (3,)Transpose (swap axes)
Section titled “Transpose (swap axes)”Transposing is a special case of reshaping — it also returns a view, never a copy.
For 2D:
import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.T)flowchart LR A["ndarray"] --> B["reshape(r, c)
same data, new grid"] A --> C["ravel() / flatten()
collapse to 1D"] A --> D["expand_dims / newaxis
add a dimension"] A --> E["squeeze()
remove size-1 dims"] A --> F["T / swapaxes()
reorder axes"]
Continue to: Broadcasting in NumPy to learn how NumPy applies operations between different shapes.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Reshape with -1
Section titled “Exercise 1 – Reshape with -1”Exercise 2 – Flatten a Matrix
Section titled “Exercise 2 – Flatten a Matrix”Exercise 3 – Column Vector with newaxis
Section titled “Exercise 3 – Column Vector with newaxis”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading