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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
