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.
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...
