Sub topic 2
Nominal and ordinal categories
This chapter assumes you can work with pandas DataFrames and know what a feature matrix is. It does not need any encoder yet. Its goal is to classify a categorical column before you choose how to encode it. That choice decides whether one-hot encoding is appropriate.
Two kinds of categorical columns
A categorical feature takes values from a fixed set of labels. Labels come in two kinds:
- Nominal categories have no meaningful order.
colorwith values red, green and blue is nominal. So arecity,payment_methodandcountry. Nothing makes "red" greater or smaller than "blue". - Ordinal categories have a natural order, but the gaps between neighbors are not defined.
sizewith values small, medium and large is ordinal. So are survey ratings from "strongly disagree" to "strongly agree", and education levels from high school to doctorate.
The difference matters because an encoding is a claim about the data. Any numeric encoding that preserves an order tells the model that the order is real. For a nominal column that claim is false. For an ordinal column, throwing the order away discards real information.
| Feature | Example values | Type | Order meaningful? | Distances meaningful? |
|---|---|---|---|---|
| `color` | red, green, blue | Nominal | No | No |
| `city` | Paris, Berlin, Rome | Nominal | No | No |
| `size` | small, medium, large | Ordinal | Yes | No |
| `satisfaction` | poor, fair, good, excellent | Ordinal | Yes | No |
| `age` in years | 23, 41, 67 | Numeric | Yes | Yes |
The last row is not categorical at all. Numeric features have both order and meaningful distances, which is why models can use them directly.
Why "ordinal" does not mean "numeric"
Ordinal data ranks the values but does not measure them. The step from small to medium is not necessarily the same size as the step from medium to large. A shirt that is "large" is not three times a "small" in any sense a model should assume.
If you code size as 0, 1, 2, you add an assumption of equal spacing. For some models that assumption is harmless, and for others it is not. The next chapter looks at that trade-off in detail. For now, remember that an ordinal column sits between nominal and numeric. You can treat it as nominal and lose the order. You can treat it as numeric and assume the spacing. Or you can pick a method that sits between the two.
Deciding which type a column is
A few questions settle most cases:
- Can you sort the values in a way that every domain expert would agree on? If not, the column is nominal.
- Does the order come from the real world, not from the alphabet or from the order in which the values appeared in the file? Only a real-world order counts.
- Would swapping two values change the meaning of the data? For nominal data you can relabel freely. For ordinal data you cannot.
One-hot encoding is the default for nominal columns because it makes no claim about order. It is also a valid fallback for ordinal columns. It treats every level as an unrelated label, which wastes the order but never invents a false one.
Recording the order explicitly
Software does not know that "medium" sits between "small" and "large". If you leave it alone, pandas and scikit-learn sort labels alphabetically, and alphabetical order is wrong for most ordinal data. Here "large" would come first, "medium" second and "small" last.
The safest habit is to write the order down in code. In pandas you do that with an ordered categorical type:
import pandas as pd
sizes = pd.Series(["small", "large", "medium", "small"])
size_type = pd.CategoricalDtype(
categories=["small", "medium", "large"],
ordered=True,
)
sizes = sizes.astype(size_type)
print(sizes.cat.codes.tolist())
print((sizes > "small").tolist())
print(sizes.max())The codes come out as [0, 2, 1, 0], which follows your declared order. The comparison sizes > "small" works because pandas now knows the order, and max() returns large. With a plain string column, max() would return small, because it is last alphabetically.
A column declared this way carries its meaning with it. Anyone reading the code can see that the order was a deliberate decision.
Setting the order in scikit-learn
scikit-learn's OrdinalEncoder turns each category into an integer. Its default is to sort the categories, which gives the alphabetical trap. The categories parameter fixes it:
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
df = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
default_enc = OrdinalEncoder()
print(default_enc.fit_transform(df).ravel())
print(default_enc.categories_)
ordered_enc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print(ordered_enc.fit_transform(df).ravel())The default encoder gives [2. 0. 1. 2.], because the categories are sorted as large, medium, small. That is the reverse of the real order. The explicit encoder gives [0. 2. 1. 0.]. The categories argument is a list with one inner list per column, in the same order as the columns you pass in.
Note that the output is floating point. OrdinalEncoder returns floats by default, so don't be surprised by 2.0 instead of 2.
Edge cases that blur the line
Real columns do not always sort neatly into nominal and ordinal. These cases come up often.
Numbers that are really labels
A zip code, a product ID or a numeric department code looks like a number but behaves like a nominal category. The value 90210 is not "bigger" than 10001 in any useful way. If you feed such a column into a model as a number, it will look for trends that do not exist. Convert it to a string or categorical type first.
Binary columns
A column with two values, such as is_member with yes and no, is a special case. With two levels, order is trivial, and a single 0/1 column carries all of the information. Whether you call it nominal or ordinal makes no practical difference. Later chapters show how the drop option of one-hot encoding reduces a two-level column to exactly this single column.
Cyclic values
Month, weekday and hour of day have an order, but it wraps around: December is followed by January. An integer code from 1 to 12 puts December and January far apart. Treat these as nominal with one-hot encoding if you have enough data. Otherwise use a cyclic transform, which the final chapter of this tutorial names among the alternatives.
Ordinal order that depends on context
Some orders hold only in one setting. Ratings of "poor" to "excellent" are stable. Priority labels like "P1" to "P4" may or may not mean the same thing across teams. If you cannot defend the order, do not encode it as one.
Ordinal with many levels
Five or six ordered levels are manageable either way. A column with fifty ordered levels, such as a detailed grade scale, makes one-hot encoding wide. In that case an ordinal code is attractive, but only if the model can use a single numeric column well.
What each model family does with the order
The right choice also depends on the model you plan to use.
- Linear and logistic regression read an integer code as a number. They assume that each step adds the same amount to the prediction. That is a strong claim for ordinal data and a false one for nominal data.
- Distance-based models such as k-nearest neighbors and support vector machines with common kernels use distances between rows. Integer codes create artificial distances.
- Tree-based models split on thresholds such as "size <= 1". They can make good use of an ordinal code, because a threshold respects order and does not need equal spacing. They still gain nothing from an invented order on a nominal column.
For nominal data, order-based codes are risky with every model family. For ordinal data, the choice is a real decision, and you should compare both options with cross-validation when it matters.
Summary of the rule
- Nominal column: use one-hot encoding. Do not use integer codes as model inputs.
- Ordinal column with a trustworthy order: record the order explicitly and consider an ordinal encoding. Remember that it assumes equal spacing.
- Ordinal column where you doubt the order or spacing: one-hot encoding is a safe default that costs only extra columns.
- Numeric-looking labels and cyclic values: look at what the values mean, not at how they are stored.
The next chapters show what goes wrong when integer codes are applied to nominal data, and then how one-hot encoding fixes it.
Exercise
A dataset has three columns: shirt_size (XS, S, M, L, XL), payment_method (card, cash, transfer) and postal_code (such as 10115, 75001, 00184). Classify each as nominal or ordinal, say what you would do with postal_code before modeling, and write the categories argument you would pass to OrdinalEncoder for shirt_size.
Show answer
shirt_size is ordinal, because sizes have a real-world order. payment_method is nominal, because no order exists among card, cash and transfer. postal_code is nominal despite its numeric look, so convert it to a string or categorical type before modeling. This also keeps leading zeros such as 00184. The argument for shirt_size is categories=[["XS", "S", "M", "L", "XL"]], a list containing one inner list in the real order. Without it the encoder would sort alphabetically and give L, M, S, XL, XS.