Menu
CoddyTech

Categories as Numbers

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 52 of 64.

Models do math, so this chapter turns words into numbers. Ordered categories, like juice sizes, get numbers in their order:

A dictionary strip reading small: 1, medium: 2, large: 3 above a column of sizes, large, small, medium, small, with arrows labelled .map(sizes) to a size_code column holding 3, 1, 2, 1

A dictionary holds the numbers; .map looks up every value, and square brackets look up one:

orders = pd.DataFrame({"juice": ["mango", "lime", "berry", "orange"],
                       "size": ["large", "small", "medium", "small"]})
sizes = {"small": 1, "medium": 2, "large": 3}
orders["size_code"] = orders["size"].map(sizes)
print(orders)
print(sizes["medium"])

This prints:

    juice    size  size_code
0   mango   large          3
1    lime   small          1
2   berry  medium          2
3  orange   small          1
2

As text the order is lost: "large" < "small" is True, alphabetically. The codes keep it.

A word missing from the dictionary, like "Large" with a capital L, becomes NaN: count those with .isna().sum().

challenge icon

Challenge

Medium

A ramen shop logs orders in ramen.csv. Its spice column runs mild, medium, hot, inferno, mildest first. The program reads a level.

  1. Add a column heat: mild is 1, up to inferno 4.
  2. Print the first 5 rows, then Mean heat: to 2 decimals.
  3. Count the orders at least as hot as level.

For another shop and the input hot:

       bowl    spice  price  heat
0      miso   medium   12.0     2
1      shio      hot   11.0     3
2     shoyu     mild   11.5     1
3      miso  inferno   12.5     4
4  tonkotsu      hot   14.0     3
Mean heat: 2.33
At least hot: 3

Try it yourself

import pandas as pd

ramen = pd.read_csv("ramen.csv")
level = input()

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Statistics for ML

Practice on your own: Online Python compiler