Column Z-Score Standardization with NumPy Broadcasting
Quick Overview
Standardize every column of a 2D NumPy array to zero mean and unit standard deviation without loops. It tests reductions along an axis, keepdims and broadcasting, population versus sample standard deviation, and how to handle constant columns.
Column Z-Score Standardization with NumPy Broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `zscore_columns(X)` that standardizes each column of a 2D array `X` as `(X - column_mean) / column_std`. Return an array of the same shape with each column at approximately 0 mean and 1 standard deviation.
For example:
```python
X = np.array([[1., 2.],
[3., 4.],
[5., 6.]])
zscore_columns(X)
# array([[-1.22474487, -1.22474487],
# [ 0. , 0. ],
# [ 1.22474487, 1.22474487]])
```
```hint Watch the shapes
Check the shape your per-column statistics come back with, and make sure it lines up with the columns of `X` when you subtract and divide.
```
### Constraints & Assumptions
- `X` is a 2D numeric array of shape `(n_rows, n_cols)`.
- Compute the per-column mean and std with `axis=0` and `keepdims=True`.
- Use the population std (`ddof=0`, the `np.std` default).
- No explicit loops. Rely on broadcasting.
### What a Strong Answer Covers
- Reducing along `axis=0` to get one mean and one standard deviation per column.
- The shape of the statistics with `keepdims=True` and how they broadcast against `X`.
- Population versus sample standard deviation, and which one the task asks for.
- Float conversion of the input and what happens to a constant column.
- A check of the output against the example.
### Follow-up Questions
- How would you avoid a divide-by-zero for a constant column?
- Why use `keepdims=True` instead of reshaping the statistics manually?
- You standardized a training set this way. How do you standardize the test set?
Overview: Standardize every column of a 2D NumPy array to zero mean and unit standard deviation without loops. It tests reductions along an axis, keepdims and broadcasting, population versus sample standard deviation, and how to handle constant columns.
Implement zscore_columns(X) that standardizes each column of a 2D array X as (X - column_mean) / column_std. Return an array of the same shape with each column at approximately 0 mean and 1 standard deviation.