Sizes a Model Can Read

Data with PythonMedium+10 XP+10

Sizes a Model Can Read

A shop wants to feed T-shirt orders to a model, so the size column needs one-hot encoding. The sizes were typed by hand, so "Large", " large" and "LARGE" all appear, and some orders have no size at all (None).

Write encode_sizes(sizes), where sizes is a list with one entry per order.

  1. Clean each size: remove spaces from both ends and make it lowercase.
  2. One-hot encode the cleaned column with pd.get_dummies, using 1 and 0 for the flags. Name the column size before encoding, so the new columns are called things like size_large.
  3. An order with no size gets 0 in every size column.

Return a dictionary with two keys:

  • "columns": the list of new column names, in the order get_dummies gives them
  • "rows": a list with one list of 1s and 0s per order, in the input order

At least one order has a size.

Examples

sizes = ["Large", " small", "LARGE", "medium "]
returns {'columns': ['size_large', 'size_medium', 'size_small'], 'rows': [[1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]]}
sizes = ["S", None, " s", "M"]
returns {'columns': ['size_m', 'size_s'], 'rows': [[0, 1], [0, 0], [0, 1], [1, 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