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.