One Row, Two Routes

Machine Learning in CodeMedium+10 XP+10

One Row, Two Routes

A bike shop's table has number columns with gaps and a word column. Prepare a new bike the same way as the training table.

Task: write prepare_row(table, number_columns, word_column, new_row).

  • table is a dict mapping column names to lists. Number columns may contain None for gaps.
  • new_row is a dict mapping each of those column names to one value (not a list). Its numbers may be None too.
  • Build a ColumnTransformer with two lines, in this order:
    • ("numbers", inner, number_columns), where inner is a Pipeline of ("fill", SimpleImputer(strategy="median")) then ("scale", StandardScaler()).
    • ("words", OneHotEncoder(handle_unknown="ignore"), [word_column]).
  • Fit it on the table only. Then transform the one-row table made from new_row.
  • Return the prepared row as a flat list of numbers, each rounded to 2 decimal places.

Tip: build the tables with pd.DataFrame(...) and make each number column float (for example with .astype(float)), so None becomes np.nan.

Examples

table = {"price": [300, None, 500, 400], "gears": [3, 7, 21, None], "type": ["city", "road", "road", "city"]}
number_columns = ["price", "gears"]
word_column = "type"
new_row = {"price": None, "gears": 7, "type": "road"}
returns [0.0, -0.37, 0.0, 1.0]
table = {"weight": [150.0, 170.0, 130.0, 110.0], "sweet": [7.0, 8.0, 3.0, 2.0], "colour": ["red", "red", "yellow", "yellow"]}
number_columns = ["weight", "sweet"]
word_column = "colour"
new_row = {"weight": 150.0, "sweet": 7.0, "colour": "green"}
returns [0.45, 0.78, 0.0, 0.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run