Compute Column Medians and Percentiles of a 2-D NumPy Array
Quick Overview
Implement two NumPy helpers that return the median and the q-th percentile of every column of a 2-D array. It tests reductions along an axis, how np.percentile interpolates between data points, the output dtype for integer input, and handling of NaN values.
Compute Column Medians and Percentiles of a 2-D NumPy Array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 2-D NumPy array `arr` of shape `(rows, cols)`, implement two functions:
- `column_median(arr)` returns the median of each column.
- `column_percentile(arr, q)` returns the `q`-th percentile of each column.
Both return a 1-D `ndarray` of length `cols`. Reduce along `axis=0`, use `np.median` for the median, and use `np.percentile` for the general case (the median is the case `q = 50`).
For example:
```python
arr = np.array([[1, 10],
[3, 20],
[5, 30]])
column_median(arr) # -> array([ 3., 20.])
column_percentile(arr, 25) # -> array([ 2., 15.])
```
```hint Check the example by hand
The 25th percentile of the column [1, 3, 5] is not one of its entries. Work out between which two sorted values it falls and how far along, then confirm that the default behavior of `np.percentile` gives the same number.
```
### Constraints & Assumptions
- `arr` is 2-D with at least one row and one column.
- `q` is between 0 and 100 inclusive.
### What a Strong Answer Covers
- Which axis the reductions run over and why that gives one value per column.
- How a percentile is computed when it falls between two data points, checked against the example.
- How the median relates to the 50th percentile.
- The dtype and shape of the result for integer input.
- The time and memory cost of the two reductions.
### Follow-up Questions
- How would you handle columns containing `NaN` values?
- What does the `method` argument of `np.percentile` control, and when would you change it?
- How would you compute several percentiles at once efficiently?
Overview: Implement two NumPy helpers that return the median and the q-th percentile of every column of a 2-D array. It tests reductions along an axis, how np.percentile interpolates between data points, the output dtype for integer input, and handling of NaN values.
Given a 2-D NumPy array arr of shape (rows, cols), implement two functions:
column_median(arr)
returns the median of each column.
column_percentile(arr, q)
returns the
q
-th percentile of each column.
Both return a 1-D ndarray of length cols. Reduce along axis=0, use np.median for the median, and use np.percentile for the general case (the median is the case q = 50).