We use np.vstack() and np.hstack() to join arrays together easily. They help us combine data by stacking arrays vertically or horizontally.
np.vstack() and np.hstack() in NumPy
import numpy as np # Vertical stack: stacks arrays row-wise (one on top of another) np.vstack((array1, array2, ...)) # Horizontal stack: stacks arrays column-wise (side by side) np.hstack((array1, array2, ...))
Both functions take a tuple of arrays as input.
Arrays must have compatible shapes: for vstack, arrays must have the same number of columns; for hstack, arrays must have the same number of rows.
import numpy as np array1 = np.array([1, 2, 3]) array2 = np.array([4, 5, 6]) # Vertical stack result_v = np.vstack((array1, array2)) print(result_v)
import numpy as np array1 = np.array([[1], [2], [3]]) array2 = np.array([[4], [5], [6]]) # Horizontal stack result_h = np.hstack((array1, array2)) print(result_h)
import numpy as np # Edge case: empty arrays empty1 = np.array([]) empty2 = np.array([]) # Vertical stack of empty arrays result_empty_v = np.vstack((empty1, empty2)) print(result_empty_v)
import numpy as np # Edge case: single element arrays single1 = np.array([10]) single2 = np.array([20]) # Horizontal stack result_single_h = np.hstack((single1, single2)) print(result_single_h)
This program shows how to stack two 1D arrays vertically and horizontally. For horizontal stacking, arrays are reshaped to columns first.
import numpy as np # Create two arrays array_one = np.array([10, 20, 30]) array_two = np.array([40, 50, 60]) print("Original arrays:") print("array_one:", array_one) print("array_two:", array_two) # Vertical stack: stack as rows stacked_vertical = np.vstack((array_one, array_two)) print("\nAfter np.vstack():") print(stacked_vertical) # Horizontal stack: stack as columns # First reshape to 2D column vectors array_one_col = array_one.reshape(-1, 1) array_two_col = array_two.reshape(-1, 1) print("\nArrays reshaped to columns:") print("array_one_col:\n", array_one_col) print("array_two_col:\n", array_two_col) stacked_horizontal = np.hstack((array_one_col, array_two_col)) print("\nAfter np.hstack():") print(stacked_horizontal)
Time complexity: Both np.vstack() and np.hstack() run in O(n) time, where n is the total number of elements in the arrays.
Space complexity: They create a new array, so space is O(n) for the combined size.
Common mistake: Trying to stack arrays with incompatible shapes causes errors. Always check shapes before stacking.
Use vstack when you want to add rows (stack arrays vertically). Use hstack when you want to add columns (stack arrays horizontally).
np.vstack() stacks arrays vertically (row-wise).
np.hstack() stacks arrays horizontally (column-wise).
Arrays must have compatible shapes to stack without errors.
Practice
np.vstack() do with arrays?Solution
Step 1: Understand vertical stacking
np.vstack()stacks arrays by adding rows one below another.Step 2: Compare with horizontal stacking
np.hstack()stacks arrays side by side by adding columns, so it is different.Final Answer:
Stacks arrays vertically, adding rows -> Option AQuick Check:
np.vstack() = vertical stack [OK]
- Confusing vertical and horizontal stacking
- Thinking vstack flattens arrays
- Assuming vstack splits arrays
a and b using NumPy?Solution
Step 1: Check function call syntax
NumPy functions use parentheses and tuples for multiple arrays, sonp.hstack((a, b))is correct.Step 2: Identify incorrect syntax
Square brackets, missing parentheses, or curly braces are invalid for function calls in Python.Final Answer:
np.hstack((a, b)) -> Option CQuick Check:
Correct function call uses parentheses and tuple [OK]
- Using square brackets instead of parentheses
- Passing arrays without tuple parentheses
- Using curly braces which are invalid
import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) result = np.vstack((x, y)) print(result)
Solution
Step 1: Understand np.vstack behavior
It stacks arrays vertically, so rows of y come below rows of x.Step 2: Combine arrays row-wise
Result has 4 rows: first two from x, next two from y, each with 2 columns.Final Answer:
[[1 2] [3 4] [5 6] [7 8]] -> Option DQuick Check:
Vertical stack adds rows below [OK]
- Confusing vstack with hstack output
- Expecting horizontal concatenation
- Misreading array shapes
import numpy as np a = np.array([1, 2, 3]) b = np.array([[4, 5, 6], [7, 8, 9]]) result = np.hstack((a, b)) print(result)
Solution
Step 1: Check shapes of arrays
ais shape (3,),bis shape (2,3). They differ in first dimension.Step 2: Understand hstack requirements
np.hstack()stacks arrays along their second axis if possible. Here,ais 1D andbis 2D, but NumPy broadcastsato shape (1,3) and stacks along axis 1, resulting in shape (3,3).Step 3: Result
No error occurs; arrays are concatenated.Final Answer:
No error, outputs concatenated array -> Option AQuick Check:
NumPy broadcasts 1D array and concatenates [OK]
- Assuming hstack requires same number of rows
- Confusing ValueError with TypeError
- Ignoring NumPy broadcasting rules
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6, 7], [8, 9, 10]])Which method correctly combines them into a single array with shape (2, 5) by stacking horizontally?
Solution
Step 1: Check shapes of arrays
ashape is (2, 2),bshape is (2, 3). Both have 2 rows, so horizontal stacking is possible.Step 2: Apply np.hstack
np.hstack((a, b))concatenates columns, resulting in shape (2, 5).Step 3: Verify other options
np.vstack((a, b))would fail due to different column counts; transposes complicate shape and are unnecessary here.Final Answer:
np.hstack((a, b)) -> Option BQuick Check:
Same rows, hstack adds columns [OK]
- Using vstack with different column counts
- Overcomplicating with transpose
- Mixing up row and column dimensions
Ready to prove it?
Pass the test and this pattern moves unknown
