Prepare Features: Text Categories and Blank Values
A model in scikit-learn computes with numbers, but real tables also hold names, such as a payment method or a type of contract, and cells where a value is simply absent. Before a model can learn from those columns, each name has to become numbers and each gap has to be filled with a value that makes sense. Done well, this lets the model use information it had to ignore before; done by habit, it quietly teaches the model something false.
Columns that hold names, not amounts
Some columns measure an amount: the months a customer has stayed, the charge on a monthly bill. Their values can be compared and added, and a bigger number means more of something. Other columns hold a name chosen from a short list: a payment method of card, cash or transfer, a contract of one month or two years. These are category columns, and each name in their list is a category.
A model that computes with numbers cannot use such a column as it is. A logistic regression multiplies every feature by a weight and adds them up, and there is no way to multiply the word cash by a weight. A decision tree asks questions such as "is the value at most 2.5?", and a word has no place on that scale. scikit-learn models expect every value to be a number, so they stop with an error when they are given text.
The tempting fix is to number the names: card becomes 1, cash 2, transfer 3. The column is now numeric, but it says things that are not true. It says cash lies between card and transfer, and that transfer is "more" than card. A tree that splits at 2.5 would then put card and cash on one side, as if they were close, only because of the numbers they were given. A model has no way to know those numbers are only labels, so it treats them as amounts, exactly as the scikit-learn guide warns: such codes "would interpret the categories as being ordered, which is often not desired".
- 1
- 2
- 3
- card
- cash
- transfer
- a split at 2.5 puts card and cash together
Not every number is an amount either. A postal code or a store number is written in digits, yet a code of 9000 is not "more" than a code of 1000: it is a name that happens to use digits, and it is a category column too. The question to ask of each column is whether its values are amounts or names, not whether they look like numbers. A yes-or-no column already written as 0 and 1 is the one easy case: it is a category with two values, and it is ready to use.
True or false?
Replacing the names card, cash and transfer with 1, 2 and 3 is a safe way to give a model a payment column.
False. The model reads the codes as amounts, so it believes cash lies between the other two and that transfer is the largest, an order the names never had.
A column of postal codes is a category column even though every value is written in digits.
True. Its values name places; no arithmetic on them means anything, so they are names, not amounts.
Missing values, and blanks that hide
A missing value is a cell with no value in it: a survey answer that was skipped, a reading a sensor never sent, a total that does not exist yet. pandas, the Python library that holds a table as a DataFrame of named columns, marks a missing number with a special value, NaN ("not a number"). To find the gaps, the method isna() returns True for every cell that holds such a marker.
A gap is not always stored as a marker. A file can hold a blank that is really a space, and pandas reads a space as text, not as missing. One such cell in a column of numbers is enough to make pandas read the whole column as text. The result is two problems at once: isna() counts nothing as missing, and the column looks like a column of words instead of amounts. When pandas reads a file, it counts a truly empty field as missing by default, but not a field that holds a space: that is text, so isna() does not see it.
| Customer | Months | total_spent (text) | after to_numeric |
|---|---|---|---|
| A | 14 | "702.50" | 702.5 |
| B | 0 | " " | NaN |
| C | 31 | "1890.00" | 1890.0 |
The fix is to turn the text into numbers and let the blanks become real missing markers. pd.to_numeric converts a column to numbers, and with errors="coerce" it turns every value it cannot read as a number into NaN instead of stopping with an error. Only then does isna() see the gaps:
import pandas as pd
table = pd.DataFrame({
"months": [14, 0, 31],
"total_spent": ["702.50", " ", "1890.00"],
})
print(table["total_spent"].isna().sum()) # 0: the blank is text
table["total_spent"] = pd.to_numeric(table["total_spent"], errors="coerce")
print(table["total_spent"].isna().sum()) # 1: now a real gap
print(table[table["total_spent"].isna()]) # the row with the gapThe last line selects the rows whose value is missing, so you can look at them before you decide anything. That look matters more than any formula, because the rows themselves usually tell you why the value is absent.
True or false?
If isna().sum() reports 0 for a column, that column has no gaps to deal with.
False. Blank text is not counted as missing. A column read as text can hide blanks until it is converted with pd.to_numeric and errors="coerce".
A single blank cell can make pandas read a whole column of numbers as text.
True. A column has one type, and a value that is not a number forces the whole column to text.
Fill a gap from the reason it is missing
Some models refuse gaps outright. LogisticRegression stops with an error when its input holds NaN, while a scikit-learn DecisionTreeClassifier can handle missing values on its own. So the gaps have to be dealt with before training. Throwing away every row with a gap is the bluntest answer, and it loses the rest of what those rows know. The usual answer is to fill each gap with a value, which scikit-learn calls imputing: inferring the value from the known part of the data.
The value to fill with should come from the reason the value is missing. Filling every gap with the column's average out of habit is easy, and often wrong. Picture a total-spent column whose only blanks belong to accounts opened this month. Those customers have not been billed yet, so the true total is zero, or at most one month's charge. The average total, perhaps hundreds, would tell the model these brand-new customers have a long history of paying, the opposite of the truth.
| Why it is missing | Example | A fill that fits |
|---|---|---|
| It does not exist yet | No total spent for an account opened today | The value it truly has: 0, or what one month adds |
| It does not apply | No internet speed for a customer without internet | A category of its own, such as "none" |
| It was not recorded | A form field someone skipped | A typical value such as the median of the training rows, perhaps with a 0/1 column marking that it was filled |
In the first two cases the reason gives back the real value, so nothing is guessed at all. Only in the last case is the value truly unknown, and then a typical value of the column is a reasonable stand-in. scikit-learn's SimpleImputer fills with the mean, the median, the most frequent value or a constant. Its add_indicator=True option also adds a column that marks which cells were filled, because the fact that a value was missing can itself tell the model something.
In pandas, fillna(value) replaces every missing marker in a column with the value you give it. Continuing the table above, where the only blank belongs to a customer with 0 months, table["total_spent"] = table["total_spent"].fillna(0) fills it with the zero that is true for them.
True or false?
Filling gaps with the column average is the standard choice, and it is always a safe one.
False. The average is one option among several. When the reason for the gap tells you the true value, such as zero spent for a brand-new account, the average gives the model a false picture.
Every scikit-learn model rejects an input that contains NaN.
False. LogisticRegression does, but decision trees and some tree ensembles in scikit-learn handle missing values on their own.
One-hot encoding: one 0 or 1 column per category
Back to the names. The way to turn a category column into numbers without inventing an order is one-hot encoding: each category gets its own new column, which holds 1 in the rows that have that category and 0 everywhere else. A payment column with three names becomes three columns, and in every row exactly one of them is 1, the "hot" one.
| payment | payment_card | payment_cash | payment_transfer |
|---|---|---|---|
| card | 1 | 0 | 0 |
| transfer | 0 | 0 | 1 |
| cash | 0 | 1 | 0 |
| card | 1 | 0 | 0 |
Each new column answers one plain yes-or-no question: "does this customer pay by cash?". No category sits between two others, and none is larger, so the false order is gone. A logistic regression can now learn a separate weight for each payment method, and a tree can ask "pays by cash?" as one of its questions. The price is width: a column with many different names becomes as many columns, which is why one-hot encoding suits columns with a short list of values.
True or false?
After one-hot encoding, each row has exactly one 1 among the columns made from one category column.
True. A row has one category in that column, so only its own column is 1 and the others are 0.
One-hot encoding a column with four different names adds one new column, holding the numbers 1 to 4.
False. It adds four columns, one per name, each holding only 0 or 1. Numbers 1 to 4 would bring back the false order.
The list of categories comes from the training rows
Which columns does the encoding create? One column per category in the list, so the list decides them. The model is trained on those exact columns, so every row it later sees must arrive with the same columns in the same order. That is why the list is fixed once, from the training rows, the part of the data the model learns from. Validation rows, kept aside to compare choices, are then encoded with that same list.
- Training rows
- fit learn the list
- card, cash, transfer categories_
- transform same 3 columns
- Model
- Training rows to fit
- fit to card, cash, transfer
- card, cash, transfer to transform
- transform to Model
scikit-learn's OneHotEncoder works this way. Its fit method reads the training rows and stores each column's categories in categories_; its transform method then encodes any rows with that stored list. sparse_output=False asks for an ordinary array, because by default the encoder returns a compressed "sparse" matrix that stores only the 1s.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"payment": ["card", "transfer", "cash", "card"]})
valid = pd.DataFrame({"payment": ["cash", "card"]})
encoder = OneHotEncoder(sparse_output=False)
encoder.fit(train) # learns the list from training rows
print(encoder.categories_) # card, cash, transfer
print(encoder.get_feature_names_out()) # payment_card, payment_cash, payment_transfer
print(encoder.transform(valid)) # [[0. 1. 0.]
# [1. 0. 0.]]The new column names join the column name and the category with an underscore, so each column says what it stands for. The output is a number with a decimal point, 0.0 or 1.0, because the encoder produces floating-point numbers by default.
A fixed list raises one question: what if a validation row holds a name the training rows never had, say voucher? By default (handle_unknown="error") the encoder stops with an error, which makes the surprise visible. With handle_unknown="ignore" it gives that row 0 in every payment column instead, so the row still has the columns the model expects.
pandas has a shortcut, pd.get_dummies, that one-hot encodes a DataFrame in one call. It has no fit step: it builds columns from whatever values are in the table it is given. Called separately on training and validation rows, it can produce different columns for each, and the model then receives columns it was never trained on. Note also that it writes True and False unless you pass dtype=int.
True or false?
The encoder should learn its list of categories from the training rows, then encode the validation rows with that same list.
True. One fixed list gives every part of the data the same columns in the same order, the ones the model was trained on.
Calling pd.get_dummies separately on training rows and on validation rows always gives both the same columns.
False. get_dummies keeps no list. A category present in only one of the parts gives that part a column the other lacks.
Seeing what the new columns are worth
Encoding and filling are done for a purpose: to let the model read columns it had to leave out. Whether they help is a question for measurement, not belief. The fair test trains the same kind of model twice with the same settings, once on the number columns alone and once with the encoded and filled columns added, and compares the two scores on the same validation rows.
- Number columns only
- Numbers plus encoded columns
- Same model, same settings
- Same model, same settings
- Scores on the same validation rows
- Number columns only to Same model, same settings
- Numbers plus encoded columns to Same model, same settings
- Same model, same settings to Scores on the same validation rows
- Same model, same settings to Scores on the same validation rows
Keeping everything else the same is what makes the difference in scores belong to the new columns. A gain can be large when a category carries much of the answer, small when the number columns already held the same information, or no gain at all; the comparison reports whichever it is, and that is the result to state.
True or false?
To judge what the encoded columns add, both models should be scored on the same validation rows.
True. With the rows, the model and its settings held the same, the only thing that differs is the columns, so the change in score belongs to them.