Python / Data Science Essentials Interview Questions
How do you stack, concatenate, and split NumPy arrays?
Combining and splitting arrays is a frequent operation in data preprocessing — assembling feature matrices from multiple sources, or splitting a dataset into folds for cross-validation.
import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6], [7, 8]]) # --- Concatenating along existing axes --- np.concatenate([a, b], axis=0) # stack rows (vertical) # [[1 2] # [3 4] # [5 6] # [7 8]] np.concatenate([a, b], axis=1) # stack columns (horizontal) # [[1 2 5 6] # [3 4 7 8]] # --- Convenience stacking functions --- np.vstack([a, b]) # vertical stack â same as axis=0 np.hstack([a, b]) # horizontal stack â same as axis=1 for 2-D np.dstack([a, b]) # depth stack (creates a 3rd axis) # stack â creates a NEW axis (different from concatenate!) np.stack([a, b], axis=0) # shape (2, 2, 2) np.stack([a, b], axis=2) # shape (2, 2, 2) â depth # --- Splitting --- big = np.arange(12).reshape(6, 2) parts = np.vsplit(big, 3) # split into 3 equal arrays along axis 0 # [array([[0,1]]), array([[2,3]]), ... ] # Split at specific indices parts = np.split(big, [2, 4], axis=0) # [0:2], [2:4], [4:] # Tile â repeat an array np.tile(a, (2, 3)) # repeat a 2 times along rows, 3 times along cols
More Related questions...