0
0
NumPydata~5 mins

np.vstack() and np.hstack() in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.vstack() do in numpy?

np.vstack() stacks arrays vertically (row-wise). It joins arrays by adding rows on top of each other.

Click to reveal answer
beginner
What is the difference between np.vstack() and np.hstack()?

np.vstack() stacks arrays vertically (adds rows). <br>np.hstack() stacks arrays horizontally (adds columns).

Click to reveal answer
beginner
Given two arrays a = np.array([1, 2]) and b = np.array([3, 4]), what is the result of np.vstack((a, b))?
array([[1, 2],
       [3, 4]])
Click to reveal answer
intermediate
What shape must arrays have to be stacked using np.hstack()?

Arrays must have the same number of rows (same first dimension) to stack horizontally.

Click to reveal answer
intermediate
Why might np.vstack() or np.hstack() raise an error?

They raise errors if arrays have incompatible shapes for stacking. For vstack, columns must match; for hstack, rows must match.

Click to reveal answer
What does np.hstack() do?
AStacks arrays vertically (adds rows)
BStacks arrays horizontally (adds columns)
CFlattens arrays into 1D
DSplits arrays into parts
If you have two arrays with shapes (2, 3) and (3, 3), can you use np.vstack() to stack them?
AYes, because rows differ
BNo, because rows differ
CYes, because columns match
DNo, because columns differ
What shape will the result have after np.hstack() of arrays with shapes (2, 3) and (2, 2)?
A(2, 5)
B(4, 3)
C(2, 1)
D(3, 2)
Which numpy function would you use to add rows to an existing array?
Anp.hstack()
Bnp.concatenate() with axis=1
Cnp.split()
Dnp.vstack()
What happens if you try to np.hstack() arrays with different number of rows?
AYou get an error about shape mismatch
BThey stack successfully
CArrays get flattened
DArrays get stacked vertically instead
Explain in your own words how np.vstack() and np.hstack() combine arrays. Give a simple example.
Think about stacking blocks either on top or side by side.
You got /3 concepts.
    What shape conditions must arrays meet to be stacked with np.vstack() and np.hstack()? Why is this important?
    Consider how rows and columns align when stacking.
    You got /3 concepts.