Before clustering customers, monthly spend has to be put on a comparable scale. The standard move is a z-score: subtract the mean and divide by the standard deviation.
Write a function zscore(values) that takes a list of numbers and returns a list of z-scores, each rounded to 2 decimals. If the standard deviation is 0, return a list of 0.0 of the same length.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import numpy as np
spend = [2, 4, 4, 4, 5, 5, 7, 9]- Step 1: `np.asarray(values, dtype=float)` converts the list once and forces float maths, avoiding integer-division surprises.
- Step 2: Compute the standard deviation once and store it. NumPy's `.std()` is the *population* standard deviation (`ddof=0`); pass `ddof=1` if an interviewer asks for the sample version.
- Step 3: Guard against `sd == 0` — a constant array would otherwise produce `nan` from a divide-by-zero.
- Step 4: `(arr - arr.mean()) / sd` is a vectorised operation: NumPy broadcasts the scalar across every element, no Python loop required.
- Step 5: `np.round(..., 2).tolist()` converts back to plain Python floats so the result is JSON-friendly.
import numpy as np
def zscore(values):
arr = np.asarray(values, dtype=float)
sd = arr.std()
if sd == 0:
return [0.0] * arr.size
return np.round((arr - arr.mean()) / sd, 2).tolist()Learn the concept first
Stuck on NumPy? These free Python lessons teach it step by step.
More NumPy questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program