Stack two 1-D NumPy arrays as the rows of a 2-D array
Quick Overview
Write a NumPy function that takes two 1-D arrays of the same length and returns a 2-D array with one input per row. It tests which joining functions add a dimension, how row order and dtypes carry through, and what happens when the lengths differ.
Stack two 1-D NumPy arrays as the rows of a 2-D array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `stack_as_rows(a, b)`. Given two 1-D NumPy arrays of equal length `n`, return a 2-D array of shape `(2, n)` whose row 0 equals `a` and whose row 1 equals `b`.
Use a stacking function such as `np.vstack` or `np.stack`. Do not preallocate an output array and fill it by index assignment.
Example:
```python
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stack_as_rows(a, b)
# array([[1, 2, 3],
# [4, 5, 6]])
```
```hint Check the shape
Before you pick a function, work out the shape each candidate returns for two 1-D inputs of length 3. Some NumPy joining functions return a longer 1-D array for 1-D inputs.
```
### What a Strong Answer Covers
- A single stacking call that returns shape `(2, n)` with the rows in argument order
- Why joining two 1-D arrays end to end gives the wrong shape
- What happens when the lengths differ or the dtypes differ
- How the call changes when the arrays should become columns
### Follow-up Questions
- How would you instead stack `a` and `b` as columns?
- What does `np.hstack((a, b))` return for the example inputs, and why?
- How would you extend the function to `k` arrays of length `n`?
Overview: Write a NumPy function that takes two 1-D arrays of the same length and returns a 2-D array with one input per row. It tests which joining functions add a dimension, how row order and dtypes carry through, and what happens when the lengths differ.
Implement stack_as_rows(a, b). Given two 1-D NumPy arrays of equal length n, return a 2-D array of shape (2, n) whose row 0 equals a and whose row 1 equals b.
Use a stacking function such as np.vstack or np.stack. Do not preallocate an output array and fill it by index assignment.
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stack_as_rows(a, b)
# array([[1, 2, 3],
# [4, 5, 6]])
What a Strong Answer Covers Guidance
A single stacking call that returns shape
(2, n)
with the rows in argument order
Why joining two 1-D arrays end to end gives the wrong shape
What happens when the lengths differ or the dtypes differ
How the call changes when the arrays should become columns
Follow-up Questions Guidance
How would you instead stack
a
and
b
as columns?
What does
np.hstack((a, b))
return for the example inputs, and why?
How would you extend the function to
k
arrays of length
n
?