Python / Data Science Essentials Interview Questions
How do NumPy array shape, reshape, and axis work?
Every NumPy array has a shape attribute — a tuple giving the size along each dimension. Shape is fundamental because most NumPy operations depend on it, and shape mismatches are the most common source of errors in numerical code.
import numpy as np a = np.arange(24) print(a.shape) # (24,) # reshape â change shape without copying data b = a.reshape(4, 6) # 4 rows, 6 columns c = a.reshape(2, 3, 4) # 3-D: 2 blocks of 3Ã4 # -1 means 'infer this dimension' d = a.reshape(6, -1) # (6, 4) â NumPy works out the 4 print(b.shape) # (4, 6) print(b.ndim) # 2 print(b.size) # 24 â total number of elements # Axes: axis=0 is rows (down), axis=1 is columns (across) m = np.array([[1, 2, 3], [4, 5, 6]]) print(m.sum(axis=0)) # [5 7 9] â sum down each column print(m.sum(axis=1)) # [6 15] â sum across each row print(m.sum()) # 21 â grand total # Flatten and ravel m.flatten() # always returns a copy m.ravel() # returns view if possible (faster)
A view shares memory with the original array — modifying the view modifies the original. reshape usually returns a view; flatten always returns a copy. Use np.shares_memory(a, b) to check.
More Related questions...