Concept Flow - np.vstack() and np.hstack()
Start with arrays
Choose stacking method
np.vstack()
Output combined array
We start with arrays, choose vertical or horizontal stacking, then combine arrays accordingly to get the output.
import numpy as np arr1 = np.array([1, 2]) arr2 = np.array([3, 4]) v_stack = np.vstack((arr1, arr2)) h_stack = np.hstack((arr1, arr2))
| Step | Action | Input Arrays | Stacking Method | Output Array |
|---|---|---|---|---|
| 1 | Define arr1 | [1, 2] | N/A | N/A |
| 2 | Define arr2 | [3, 4] | N/A | N/A |
| 3 | Apply np.vstack | [[1, 2], [3, 4]] | Vertical stack | [[1 2] [3 4]] |
| 4 | Apply np.hstack | [1, 2], [3, 4] | Horizontal stack | [1 2 3 4] |
| 5 | End | N/A | N/A | N/A |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| arr1 | undefined | [1 2] | [1 2] | [1 2] | [1 2] | [1 2] |
| arr2 | undefined | undefined | [3 4] | [3 4] | [3 4] | [3 4] |
| v_stack | undefined | undefined | undefined | [[1 2] [3 4]] | [[1 2] [3 4]] | [[1 2] [3 4]] |
| h_stack | undefined | undefined | undefined | undefined | [1 2 3 4] | [1 2 3 4] |
np.vstack() stacks arrays vertically (adds rows). np.hstack() stacks arrays horizontally (adds columns). Input arrays must have compatible shapes. 1D arrays become 2D in vstack, stay 1D in hstack. Use for combining arrays along different axes.
np.vstack() do with arrays?np.vstack() stacks arrays by adding rows one below another.np.hstack() stacks arrays side by side by adding columns, so it is different.a and b using NumPy?np.hstack((a, b)) is correct.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)
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)
a is shape (3,), b is shape (2,3). They differ in first dimension.np.hstack() stacks arrays along their second axis if possible. Here, a is 1D and b is 2D, but NumPy broadcasts a to shape (1,3) and stacks along axis 1, resulting in shape (3,3).a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6, 7], [8, 9, 10]])a shape is (2, 2), b shape is (2, 3). Both have 2 rows, so horizontal stacking is possible.np.hstack((a, b)) concatenates columns, resulting in shape (2, 5).np.vstack((a, b)) would fail due to different column counts; transposes complicate shape and are unnecessary here.Pass the test and this pattern moves unknown