875. Group-by mean without a Python loop
Why it matters Feature pipelines aggregate per user, per document or per token all the time. Knowing the NumPy version of GROUP BY saves you from pandas when you cannot use it.
group_mean(keys, values) returns the mean value for each distinct key.
Inputs: keys is a list or ndarray of ints, values a list or ndarray of floats of the same length (length >= 1).
Return a tuple (unique_keys, means): unique_keys is a list of Python ints in increasing order, means is an ndarray of floats in the same order. No rounding.
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 30 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def group_mean(keys, values)Example 1
Input: group_mean([2, 1, 2, 5], [1.0, 4.0, 3.0, 10.0])
Output: ([1, 2, 5], [4.0, 2.0, 10.0])
Example 2
Input: keys = [7], values = [3.5]
Output: ([7], [3.5])
Example 3
Input: keys = [-1, -1, 0], values = [1.0, 2.0, 9.0]
Output: ([-1, 0], [1.5, 9.0])
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Map keys to dense ids with np.unique(return_inverse=True).
Hint 2
np.bincount(inv, weights=values) gives per-group sums.
Hint 3
Divide by np.bincount(inv).
Common mistakes
- Sorting keys and values separately so they no longer line up.
- Forgetting that keys can be negative (bincount needs the inverse ids).
- Returning numpy ints in the key list.
Understand the idea
np.unique(..., return_inverse=True) maps every key to a dense group index 0 .. g - 1. np.bincount with weights then sums values per group in one pass, and a second bincount counts rows. Dividing gives the means. pandas groupby does the same thing internally.
Shapes and data flow
keys, values: (n,). inverse: (n,). sums, counts: (g,).