Compute per-group OLS slopes in pandas and return them as a Series

Quick Overview

Write a pandas function that fits a simple linear regression of y on x within each group and returns the slopes as a named, sorted float Series. It tests the closed-form OLS slope, vectorized groupby work, exact output contracts and the zero-variance case.

Compute per-group OLS slopes in pandas and return them as a Series

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `def groupwise_slopes(df: pd.DataFrame) -> pd.Series`. The input has columns `group` (string), `x` (float) and `y` (float). Fit a simple OLS regression of `y` on `x` (with an intercept) separately within each group and return each group's slope. - Return the slope (not the intercept) as a float64 `pd.Series` named `slope`. - Index it by group label with index name `group`, sorted ascending. - The result is compared with `pandas.testing.assert_series_equal`, so the index name, the Series name, the dtype and the order must match along with the values. ```python df = pd.DataFrame({ "group": ["a", "a", "a", "b", "b", "b"], "x": [0.0, 1.0, 2.0, 0.0, 1.0, 2.0], "y": [1.0, 3.0, 5.0, 0.0, -1.0, -2.0], }) groupwise_slopes(df) # group # a 2.0 # b -1.0 # Name: slope, dtype: float64 ``` ```hint A closed form per group With one predictor and an intercept, the least-squares slope can be written using only sums of centered values within the group. You do not need a model object per group. ``` ```hint What the grader compares `assert_series_equal` checks more than the numbers. Check the Series name, the index name, the dtype and the order of your result before returning it. ``` ### Constraints & Assumptions - The grader uses 3 groups with at least 5 rows each. - Every group has a distinct non-zero slope, and its `x` values are not all equal. ### What a Strong Answer Covers - Uses the closed-form slope (covariance of x and y over the variance of x) within each group and explains why it equals the OLS estimate - Keeps the normalization consistent so the n or n-1 factors cancel - Meets the full output contract: Series name, index name, float64 dtype and ascending order - Says what happens for a group with constant `x` and how the code guards against it - Gives the complexity and avoids a Python-level loop when there are many groups ### Follow-up Questions - How would you handle a group where `x` is constant (zero variance)? - How would this scale to millions of rows and thousands of groups? - How would you also return each group's intercept and the standard error of its slope? - What changes if some rows have a missing `x` or `y`?

Overview: Write a pandas function that fits a simple linear regression of y on x within each group and returns the slopes as a named, sorted float Series. It tests the closed-form OLS slope, vectorized groupby work, exact output contracts and the zero-variance case.

General logo
General
Nov 24, 2026
mediumData ScientistOtherMachine Learning
0
0

Implement def groupwise_slopes(df: pd.DataFrame) -> pd.Series. The input has columns group (string), x (float) and y (float). Fit a simple OLS regression of y on x (with an intercept) separately within each group and return each group's slope.

  • Return the slope (not the intercept) as a float64 pd.Series named slope .
  • Index it by group label with index name group , sorted ascending.
  • The result is compared with pandas.testing.assert_series_equal , so the index name, the Series name, the dtype and the order must match along with the values.
df = pd.DataFrame({
    "group": ["a", "a", "a", "b", "b", "b"],
    "x": [0.0, 1.0, 2.0, 0.0, 1.0, 2.0],
    "y": [1.0, 3.0, 5.0, 0.0, -1.0, -2.0],
})
groupwise_slopes(df)
# group
# a    2.0
# b   -1.0
# Name: slope, dtype: float64

Constraints & Assumptions

  • The grader uses 3 groups with at least 5 rows each.
  • Every group has a distinct non-zero slope, and its x values are not all equal.

What a Strong Answer Covers Guidance

  • Uses the closed-form slope (covariance of x and y over the variance of x) within each group and explains why it equals the OLS estimate
  • Keeps the normalization consistent so the n or n-1 factors cancel
  • Meets the full output contract: Series name, index name, float64 dtype and ascending order
  • Says what happens for a group with constant x and how the code guards against it
  • Gives the complexity and avoids a Python-level loop when there are many groups

Follow-up Questions Guidance

  • How would you handle a group where x is constant (zero variance)?
  • How would this scale to millions of rows and thousands of groups?
  • How would you also return each group's intercept and the standard error of its slope?
  • What changes if some rows have a missing x or y ?