Frequency Encoding: How Common Is Each Category?

Feature EngineeringEasy+10 XP+10

Frequency Encoding: How Common Is Each Category?

Frequency encoding replaces each category with how common it is — one column, no target involved, and no leakage to worry about.

encodingc=how many rows have category ctotal rowsencoding_c = \frac{\text{how many rows have category } c}{\text{total rows}}encodingc​=total rowshow many rows have category c​

Task: write frequency_encode(values) returning the encoding for each row, rounded to 4 decimal places.

  • Return one value per row, in the original order. Rows sharing a category share an encoding.
  • Divide by the total number of rows, so the distinct encodings don't sum to 1 — but every row's encoding does sum to 1 across the dataset.
  • Categories may be numbers or strings.
  • If every row is the same category, every encoding is 1.0.

The bet this encoding makes is that rarity itself is informative, and surprisingly often it is. A rare browser version correlates with fraud; a rare product category behaves differently from a bestseller; a rare job title in a salary model genuinely marks an unusual row. None of that needs the target to discover.

Its obvious failure mode is collisions: two categories appearing exactly the same number of times get exactly the same encoding, and the model can no longer tell them apart. In the long tail of a high-cardinality column, where thousands of categories appear once each, that's nearly everything — which is why frequency encoding is usually one signal among several rather than a replacement for the category.

Examples

values = ['a', 'a', 'b', 'c']
returns [0.5, 0.5, 0.25, 0.25]
values = ['a', 'a', 'a', 'b', 'c']
returns [0.6, 0.6, 0.6, 0.2, 0.2]

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