Equal-Width and Equal-Frequency Binning Transformer

Quick Overview

Implement a transformer that learns equal-width or equal-frequency bin edges for each DataFrame column and maps new values to integer bin codes. It tests edge computation with numpy, boundary and clipping rules, NaN and constant-column handling, and keeping transform free of leakage.

Equal-Width and Equal-Frequency Binning Transformer

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `KBinsTransformer(n_bins=5, strategy="uniform")` with `fit(X)`, `transform(X)` and `fit_transform(X)` over numeric DataFrame columns. `fit` learns per-column edges and returns `self`. `transform` returns integer bin codes using only the fitted edges. The transformer must meet these requirements: - `"uniform"` edges are `np.linspace(min, max, n_bins + 1)`. `"quantile"` edges are `np.quantile` (default linear interpolation) at `linspace(0, 1, n_bins + 1)`. NaNs are ignored in fit. - Collapse duplicate edges with `np.unique`. Store `edges_[col]` and `n_bins_[col] = max(len(edges) - 1, 1)`. - Bins are `[e0, e1), ..., [e_{k-1}, e_k]`. Values outside the range clip to bin `0` or the last bin. A constant column maps to all `0`. - NaN at transform time maps to `-1`. The output is an `int64` DataFrame with the input index and the columns in fit order. Inputs are not mutated. - An unknown `strategy` raises `ValueError` on `fit`. Example: ```python b = KBinsTransformer(n_bins=5, strategy="uniform").fit(pd.DataFrame({"a": np.arange(11.0)})) b.edges_["a"] # [0, 2, 4, 6, 8, 10] b.transform(pd.DataFrame({"a": [-100.0, 1.9, 2.0, 9.99, 10.0, np.nan]})) # a: [0, 0, 1, 4, 4, -1] (int64) q = KBinsTransformer(n_bins=4, strategy="quantile").fit(pd.DataFrame({"x": [0.0, 0, 0, 0, 0, 0, 1, 2]})) q.edges_["x"], q.n_bins_["x"] # [0.0, 0.25, 2.0], 2 ``` ```hint Let the search do the clipping Think about which of the edges a binary search needs to see so that every real number, including values far outside the training range, lands on a code from 0 to k-1. ``` ```hint Test the boundaries The last bin is closed on both ends and the others are closed only on the left. Check the training maximum, a value exactly on an interior edge, a constant column and a NaN. ``` ### Clarifying Questions to Ask - What should `fit` do with a column that has no non-missing values? - Should `n_bins` be validated, for example by rejecting 0, negative values or floats? - If a fitted column is missing at transform time, or the frame has extra columns, should `transform` raise or ignore them? ### What a Strong Answer Covers - Edges for both strategies computed from the non-missing training values, with duplicates collapsed and the bin count recorded per column. - A bin assignment that is left-closed, puts the training maximum in the last bin, and clips out-of-range values. - The special cases: constant columns, NaN at transform time, and the `int64` output with the input index and fit-time column order. - Using only fitted state in `transform` and leaving the input unchanged. - The cost of fit and transform per column. ### Follow-up Questions - When would you pick quantile bins over uniform bins, and how does each behave on a heavily skewed column? - How would you return one-hot bin indicators instead of ordinal codes, and which models need them? - How would you compute quantile edges on a column too large to fit in memory? - Binning throws away where a value sits inside its bin. When does it still help a model?

Overview: Implement a transformer that learns equal-width or equal-frequency bin edges for each DataFrame column and maps new values to integer bin codes. It tests edge computation with numpy, boundary and clipping rules, NaN and constant-column handling, and keeping transform free of leakage.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement KBinsTransformer(n_bins=5, strategy="uniform") with fit(X), transform(X) and fit_transform(X) over numeric DataFrame columns. fit learns per-column edges and returns self. transform returns integer bin codes using only the fitted edges.

The transformer must meet these requirements:

  • "uniform" edges are np.linspace(min, max, n_bins + 1) . "quantile" edges are np.quantile (default linear interpolation) at linspace(0, 1, n_bins + 1) . NaNs are ignored in fit.
  • Collapse duplicate edges with np.unique . Store edges_[col] and n_bins_[col] = max(len(edges) - 1, 1) .
  • Bins are [e0, e1), ..., [e_{k-1}, e_k] . Values outside the range clip to bin 0 or the last bin. A constant column maps to all 0 .
  • NaN at transform time maps to -1 . The output is an int64 DataFrame with the input index and the columns in fit order. Inputs are not mutated.
  • An unknown strategy raises ValueError on fit .

Example:

b = KBinsTransformer(n_bins=5, strategy="uniform").fit(pd.DataFrame({"a": np.arange(11.0)}))
b.edges_["a"]   # [0, 2, 4, 6, 8, 10]
b.transform(pd.DataFrame({"a": [-100.0, 1.9, 2.0, 9.99, 10.0, np.nan]}))
# a: [0, 0, 1, 4, 4, -1]  (int64)

q = KBinsTransformer(n_bins=4, strategy="quantile").fit(pd.DataFrame({"x": [0.0, 0, 0, 0, 0, 0, 1, 2]}))
q.edges_["x"], q.n_bins_["x"]   # [0.0, 0.25, 2.0], 2

Clarifying Questions to Ask Guidance

  • What should fit do with a column that has no non-missing values?
  • Should n_bins be validated, for example by rejecting 0, negative values or floats?
  • If a fitted column is missing at transform time, or the frame has extra columns, should transform raise or ignore them?

What a Strong Answer Covers Guidance

  • Edges for both strategies computed from the non-missing training values, with duplicates collapsed and the bin count recorded per column.
  • A bin assignment that is left-closed, puts the training maximum in the last bin, and clips out-of-range values.
  • The special cases: constant columns, NaN at transform time, and the int64 output with the input index and fit-time column order.
  • Using only fitted state in transform and leaving the input unchanged.
  • The cost of fit and transform per column.

Follow-up Questions Guidance

  • When would you pick quantile bins over uniform bins, and how does each behave on a heavily skewed column?
  • How would you return one-hot bin indicators instead of ordinal codes, and which models need them?
  • How would you compute quantile edges on a column too large to fit in memory?
  • Binning throws away where a value sits inside its bin. When does it still help a model?