Recover group means from dummy-variable OLS coefficients
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def group_means_from_coefs(df: pd.DataFrame) -> pd.Series`. `df` has columns `y` (float) and `g` (object, levels `'a'`, `'b'`, `'c'`). Fit an OLS regression with an intercept of `y` on dummies for `g` alone, with `'a'` as the reference level, and recover each group's mean from the coefficients.
Requirements:
- The reference group's mean is the intercept; each other group's mean is the intercept plus that group's dummy coefficient.
- Do not use `groupby` or any direct per-group averaging for the returned values.
- Return a `pd.Series` with index exactly `['a', 'b', 'c']`, `float64` values, and name `'group_mean'`.
- Use `statsmodels` (for example `smf.ols` with `C(g)`) or a manual design matrix.
Example:
```python
df = pd.DataFrame({
'y': [1.0, 3.0, 10.0, 14.0, 20.0, 20.0],
'g': ['a', 'a', 'b', 'b', 'c', 'c'],
})
group_means_from_coefs(df)
# a 2.0 (intercept)
# b 12.0 (intercept + b_coef)
# c 20.0 (intercept + c_coef)
# Name: group_mean, dtype: float64
```
```hint Follow one row through the model
Write out the fitted value for a row in group `'a'`, then for a row in group `'b'`. Which parameters does each row use?
```
```hint Know which level is the reference
Check how your encoding chooses the dropped level and how the fitted parameters are named, so you read the right coefficient for each group.
```
### Constraints & Assumptions
- `y` is a float column and `g` is an object column whose values are `'a'`, `'b'` or `'c'`.
- Each of the three levels appears at least once.
### What a Strong Answer Covers
- Encoding `g` with `'a'` as the reference and fitting OLS with an intercept on the dummies only.
- Mapping the fitted parameters back to the three group means.
- Why the reconstructed values equal the sample means exactly in this model.
- Avoiding the dummy variable trap and reading coefficients by the right name or position.
- Returning a Series with the exact index, dtype and name.
### Follow-up Questions
- What changes if you drop the intercept and use one dummy per level?
- Why do the reconstructed means match the sample means exactly here, and what breaks that if you add a continuous covariate?
- How would you get a standard error for group `'b'`'s mean from the fitted model?
- How would you test whether groups `'b'` and `'c'` have the same mean using the same fit?
Overview: Fit an OLS regression of an outcome on dummy variables for a three-level categorical feature and rebuild each group's mean from the intercept and dummy coefficients. It tests treatment coding, reference levels, the dummy variable trap and why a saturated model reproduces the sample means.