Solving tips
- Standardization is per-column: subtract each column's mean, divide by its standard deviation. Use axis=0 so NumPy reduces down the rows.
- Broadcasting handles the subtract-and-divide across all rows at once — no Python loop over columns.
- A constant column has zero standard deviation; guard it so you return zeros for that column instead of dividing by zero.
Standardization (the z-score transform) rescales each feature so it has zero mean and unit variance. It is a routine preprocessing step for models that are sensitive to feature scale, and interviewers ask for it to check that you can reduce along the right axis and handle the degenerate constant-column case.
Definition
For a column x with mean mu and standard deviation sigma, the standardized value of each entry is:
z[i] = (x[i] - mu) / sigma
The transform is applied independently to every column of the input matrix.
Task
Complete standardize(X) so it returns a new array of the same shape where each column has mean 0 and standard deviation 1. X is a 2-D NumPy array with rows as samples and columns as features. If a column has zero variance (all entries equal), return that column as all zeros rather than dividing by zero. Do not call sklearn or any built-in scaler.
Example
X = np.array([[1.0, 10.0, 5.0],
[2.0, 20.0, 5.0],
[3.0, 30.0, 5.0]])
standardize(X)
# -> array([[-1.22474487, -1.22474487, 0. ],
# [ 0. , 0. , 0. ],
# [ 1.22474487, 1.22474487, 0. ]])
The first two columns become [-1.2247, 0, 1.2247] after centering and scaling; the third column is constant, so it maps to all zeros.
Constraints
1 <= n <= 10^6,1 <= d <= 10^3; use vectorized NumPy, not a per-column Python loop.- Use the population standard deviation (
ddof=0). - Values fit in float64.