Repeat each element of a NumPy array n times in a row
Quick Overview
Write a NumPy function that repeats each element of a 1-D array n times in a row. It tests the difference between repeating elements and tiling the whole array, edge cases such as a zero count, and related tools like per-element counts and the axis argument.
Repeat each element of a NumPy array n times in a row
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `repeat_each_element(a, n)` that takes a 1-D NumPy array `a` and integer `n`, and returns a new 1-D array where each element appears `n` times consecutively (not the whole sequence tiled).
Requirements:
- Use `np.repeat`, not `np.tile`.
For example:
```python
a = np.array([1, 2, 3]); n = 2
repeat_each_element(a, n)
# array([1, 1, 2, 2, 3, 3])
# contrast: np.tile(a, n) -> array([1, 2, 3, 1, 2, 3])
```
```hint Edge behavior
Check what `np.repeat` returns for `n = 0`, and what it does when you leave out `axis` and the input is not 1-D.
```
### What a Strong Answer Covers
- A result that keeps the copies of each element next to each other and the elements in their original order.
- The difference between repeating each element and repeating the whole sequence.
- Behavior for `n = 0`, a negative or non-integer `n`, and an empty array.
- The size and dtype of the output and the cost of building it.
### Follow-up Questions
- How would you repeat each element a different number of times?
- How does `np.repeat` behave on a 2-D array with and without `axis`?
- How would you produce the same output without `np.repeat`, for example with broadcasting or indexing?
- How would you repeat the rows of a pandas DataFrame according to a count column?
Overview: Write a NumPy function that repeats each element of a 1-D array n times in a row. It tests the difference between repeating elements and tiling the whole array, edge cases such as a zero count, and related tools like per-element counts and the axis argument.
Write repeat_each_element(a, n) that takes a 1-D NumPy array a and integer n, and returns a new 1-D array where each element appears n times consecutively (not the whole sequence tiled).