Concepts / Handling Categorical Variables

Handling Categorical Variables

The result is a categorical-style feature that can be encoded like any other category.

  • Programming

Two Versions of the Same Spreadsheet

Imagine two people given the same spreadsheet. One sees a column of city names. The other sees that same column already translated into a set of yes-or-no indicators, one per city. Both people have the same facts, yet a learning method can only work with the second version, because it needs numbers in every cell. This article follows that translation step by step: how a label becomes a row of zeros and ones, how a continuous number becomes a bin label, and how new columns can be built from existing ones.

The question at the center of this article is how to move from raw columns to representations a learning method can use well, and what it means for the features you choose to match the method you apply. Feature engineering is the process of creating new features from existing ones so that a model has better material to learn from. The features chosen, and how well they fit the machine learning method, often matter more to the final result than any other single decision in the pipeline.

How a Label Becomes a One-Hot Vector

Definition

A categorical variable holds labels rather than quantities, such as a color or a product type. One-hot encoding replaces one column of labels with several columns of zeros and ones, one column for each possible category. In each row, exactly one of those columns is set to 1, and that column marks which category the row belongs to.

The mechanism has two phases. In the first phase you fix an ordered list of every category that appears in the data. In the second phase, for each value, you build a vector the same length as that list and place a 1 at the position of its category and a 0 everywhere else. Because each category gets its own position, the encoding does not force any ordering on the categories that the original labels did not have. The label red is not treated as smaller or larger than green; it simply occupies its own column.

is_red1is_green0is_blue0
Which column is set to 1 when the value is red, and which columns stay at 0?
Worked example

Encoding a color column

A column holds the colors red, green, and blue, and each row has one of them. Encode the rows with one-hot vectors.

  1. 1
    Fix the category list

    Write the categories in a fixed order: red, green, blue. Position 0 is red, position 1 is green, position 2 is blue.

  2. 2
    Make a vector of the same length

    Every encoded value is a vector with three cells, one per category.

  3. 3
    Encode a red row

    Red sits at position 0, so the vector gets a 1 at position 0 and 0 elsewhere: [1, 0, 0].

  4. 4
    Encode a green row

    Green sits at position 1, so the vector is [0, 1, 0].

  5. 5
    Encode a blue row

    Blue sits at position 2, so the vector is [0, 0, 1].

Result

The single label column has become three numeric columns. In every row exactly one column is 1, and that column identifies the row's category.

Key point

Each row of the encoded table has exactly one 1. If you ever see a row with two 1s or none in a one-hot block, the encoding has gone wrong.

Why Representation Decides What a Model Can Use

A learning method can only compute with numbers in every cell. A raw text label such as red gives a linear model no quantity to multiply by a weight, so the model cannot draw a useful boundary from it directly. Once the same information is expressed as encoded numeric columns, the weighted sum has something to work with. The facts did not change between the two versions of the spreadsheet; only the representation did.

The source also makes a point about method choice. Flexible nonlinear models such as random forests and SVMs may learn complex tasks without explicitly expanding the feature space. So whether you need to hand-build polynomial or binned features depends on the method you pair them with. The match between features and method is the deciding factor.

RepresentationWhat it doesWhat a linear model gets from it
Raw label textStores a category as a wordNo numeric quantity to weight directly
One-hot columnsStores each category as its own 0 or 1 columnNumeric cells, with no ordering forced onto categories
Binned labelGroups a continuous value into a rangeA categorical-style feature that can then be one-hot encoded
Polynomial or interaction columnAdds a new column built from existing onesA way to express curvature or joint effects through the same weighted sum

Each representation changes what the model can express, even though the underlying facts stay the same.

Turning a Continuous Value into a Bin Label

Binning creates new features by grouping a continuous variable into bins. Instead of treating age as a single running number, you assign each value to the range it falls in, such as child, adult, or senior. The result is a categorical-style feature that can be encoded like any other category. This is why binning and one-hot encoding often appear together. Binning trades fine detail for a clearer structure: two ages in the same bin become indistinguishable to the model.

childunder 13adult13 to 64senior65 and over
Given the bin ranges, which interval does the value 42 fall into, and what label and index does it receive?
Worked example

Binning an age value

Using the bins child (under 13), adult (13 to 64), and senior (65 and over), find the bin label for an age of 42, then encode it.

  1. 1
    Read the bin edges

    The edges split the number line at 13 and at 65. The bins are below 13, from 13 up to 65, and 65 and above.

  2. 2
    Locate the value

    42 is greater than or equal to 13 and less than 65, so it falls in the middle interval.

  3. 3
    Assign the label

    The middle interval is named adult, so the bin label for this row is adult.

  4. 4
    Encode the label

    With the bin order child, adult, senior, adult sits at index 1, so the one-hot vector is [0, 1, 0].

Result

The continuous value 42 becomes the categorical label adult, which can then be encoded as [0, 1, 0].

Building Polynomial and Interaction Features

Another way to create new features is by adding polynomial and interaction terms. A polynomial term takes an existing feature and raises it to a power, such as $x^{2}$. An interaction term multiplies two different features together, such as $x_1 x_2$. Both kinds of term are new columns built from the original ones, and both give the model a way to express relationships that a single raw column cannot express on its own.

x1raw inputx1 squaredpolynomial termx2raw inputx2 squaredpolynomial termx1 times x2interaction termsquaresquaremultiplymultiply
How do the raw inputs x1 and x2 expand into the new columns x1 squared, x2 squared, and x1 times x2?

Why does this help a linear model? A linear model combines its inputs with a weighted sum, so on its own it cannot bend a relationship. Adding x squared or x1 times x2 as columns lets the same weighted-sum machinery capture curvature or joint effects. The model still only adds weighted columns; the new columns are what carry the curvature or the joint effect.

Worked example

Adding an interaction column

Two raw inputs for one row are x1 = 3 and x2 = 2. Build the new columns that a linear model could use.

  1. 1
    Keep the raw columns

    The row starts with x1 = 3 and x2 = 2.

  2. 2
    Build the polynomial columns

    x1 squared is 9 and x2 squared is 4. These are new columns built from the originals.

  3. 3
    Build the interaction column

    x1 times x2 is 6. This column carries the joint effect of the two inputs.

  4. 4
    Form the feature row

    The row now has five entries: 3, 2, 9, 4, and 6. The linear model weights each one.

Result

The single row of two raw values has become a row of five features. The weighted sum can now include curvature and a joint effect, which it could not express from x1 and x2 alone.

Mistakes Beginners Make with Encodings

  • Common mistake

    Feeding raw label text to a linear model and expecting it to find patterns in the words

    What it looks like

    A column with the values red, green, and blue is passed directly to the model as text.

    Why it fails

    A linear model combines numeric inputs with a weighted sum. A text label gives it no quantity to weight.

    Do this instead

    Represent the categories numerically, for example with one-hot columns, before the model sees them.

  • Common mistake

    Assuming the encoding implies an order among categories

    What it looks like

    Reading the vector [0, 1, 0] as meaning green is between red and blue.

    Why it fails

    Each category gets its own position in the vector. The encoding does not force any ordering that the original labels did not have.

    Do this instead

    Treat each one-hot column as a separate yes-or-no indicator, one per category.

  • Common mistake

    Forgetting that binning throws away fine detail

    What it looks like

    Two ages, 14 and 60, both become adult and the model can no longer tell them apart.

    Why it fails

    Binning trades fine detail for a clearer structure. Values inside one bin share the same label.

    Do this instead

    Choose bin edges deliberately, knowing that values inside a bin are treated alike.

  • Common mistake

    Adding polynomial or interaction columns to every model by default

    What it looks like

    Building x squared and x1 times x2 columns before training a random forest.

    Why it fails

    The source notes that flexible nonlinear methods may learn complex tasks without explicitly expanding the feature space, so the extra columns are not always needed.

    Do this instead

    Decide on engineered features by considering which method you will use.

Predicting an Encoding Before You Check

What do you think happens?

The categories are fixed in the order red, green, blue. What is the one-hot vector for a green row?

  • [1, 0, 0]

  • [0, 1, 0]

  • [0, 0, 1]

  • [0, 1, 1]

Reveal answer
Answer:

[0, 1, 0]

Green is at position 1 in the fixed category list, so that position gets a 1 and every other position gets a 0.

EASY

A column has the categories small, medium, and large, in that fixed order. Write the one-hot vector for a row whose value is large. Then explain in one sentence why this encoding does not claim that large is greater than small.

Hints
  • Locate large in the fixed category list and find its position.
  • Remember that each category gets its own position and the others are 0.

Key Takeaways

  • A categorical variable holds labels such as colors or product types. One-hot encoding replaces that column with one 0-or-1 column per category, with exactly one column set to 1 in each row.
  • A learning method can only use numbers in every cell, so the representation of data determines what a method like a linear model can use.
  • Binning groups a continuous variable into ranges, producing a categorical-style label that can then be encoded, at the cost of fine detail.
  • Polynomial terms such as x squared and interaction terms such as x1 times x2 are new columns that let a linear model express curvature and joint effects through its weighted sum.
  • Whether to build these engineered features depends on the method: flexible nonlinear models such as random forests and SVMs may learn complex tasks without explicitly expanding the feature space.

Related concepts

More concepts starting with H