Array Stacking
Problem Statement
Combine multiple arrays using stacking operations.
Background
NumPy provides several stacking functions:
- np.vstack - vertical stack (row-wise)
- np.hstack - horizontal stack (column-wise)
- np.concatenate - general concatenation
- np.stack - stack along new axis
Your Task
Write a function stack_arrays(arr1, arr2) that combines two 1D arrays.
Output Format
Return a dictionary with:
- "vertical": vstack result (2 rows) as list
- "horizontal": hstack result (1 longer row) as list
- "as_columns": Side by side as columns as list
Example:
arr1 = [1, 2, 3], arr2 = [4, 5, 6]
{'vertical': [[1, 2, 3], [4, 5, 6]], 'horizontal': [1, 2, 3, 4, 5, 6], 'as_columns': [[1, 4], [2, 5], [3, 6]]}vstack creates rows, hstack concatenates, column_stack pairs elements
Constraints:
- Both arrays have the same length
- Arrays are 1D
More from NumPy Foundations
1. Background Knowledge
NumPy arrays are the foundational data structure for numerical computing in Python, enabling efficient vectorized operations on multi-dimensional data without explicit loops. Stacking refers to combining multiple arrays into a single larger array along specified axes, which is essential for reshaping data in scientific computing pipelines. Key functions include np.vstack (stacks along the vertical axis, i.e., axis 0, creating new rows), np.hstack (stacks along the horizontal axis, i.e., axis 1, appending columns), np.stack (stacks along a new axis), and np.concatenate (general-purpose joining along existing axes).
For 1D arrays like [1, 2, 3] and [4, 5, 6], stacking transforms them into 2D structures: vertical stacking yields a 2×3 array (rows), horizontal yields a 1×6 array (extended row), and column-wise stacking (via np.column_stack or transposition) yields a 3×2 array (side-by-side columns). Understanding array dimensions (.shape) and axes is crucial: axis 0 grows "down" (rows), axis 1 grows "right" (columns). Arrays must have compatible shapes for stacking—e.g., same length for vstack on 1D inputs.
2. Algorithm/Approach
The general pattern for array stacking problems is:
- Identify input array shapes and compatibility (e.g., both 1D with equal length for row-wise operations).
- Apply the appropriate stacking function based on the desired output shape:
| Operation | Function | Result Shape (for equal-length 1D) |
|---|---|---|
| Vertical | np.vstack | 2 × N |
| Horizontal | np.hstack | 1 × 2N |
| Columns | np.column_stack or np.vstack + transpose | N × 2 |
- Convert NumPy arrays to lists for dictionary output, preserving the exact structure. This leverages NumPy's vectorized efficiency, avoiding manual loops.
3. Step-by-Step Strategy
- Import NumPy: Ensure import numpy as np is available.
- Validate inputs: Check arr1 and arr2 are 1D NumPy arrays of equal length (use arr1.shape == arr2.shape and arr1.ndim == 1).
- Compute vertical stack: Use np.vstack((arr1, arr2)) → 2D array with shape (2, len(arr1)).
- Compute horizontal stack: Use np.hstack((arr1, arr2)) → 1D array with shape (2 * len(arr1),).
- Compute column stack: Use np.column_stack((arr1, arr2)) → 2D array with shape (len(arr1), 2).
- Convert to lists: Apply .tolist() to each result (handles nested structure automatically).
- Return dictionary: {"vertical": vert_list, "horizontal": horiz_list, "as_columns": cols_list}.
- Test shapes: Verify outputs match sample (e.g., vertical has 2 sublists of length 3).
4. Common Pitfalls
- Shape mismatch: vstack fails if arrays have different lengths; use padding or slicing if needed (not required here).
- Dimension confusion: hstack on 1D keeps 1D output; ensure no premature .reshape().
- List conversion: .tolist() on 2D arrays gives nested lists; direct list() may flatten unexpectedly.
- Input types: Function assumes NumPy arrays; add np.asarray() if lists are passed.
- Axis errors: For custom stacking, misuse of axis in concatenate (e.g., axis=1 on 1D needs reshape).
- Mutable inputs: Stacking creates views/copies; original arrays unchanged, but verify with id().
5. Time & Space Complexity
- Time: O(N) per stacking operation, where N is array length (constant-time copies in contiguous memory). Total: O(N) for all three.
- Space: O(N) extra for each output array (total O(3N) or O(N)); outputs are shallow copies unless modified. NumPy optimizes via contiguous memory and vectorization, scaling linearly for large N.