Numerical, Categorical, Binary and Ordinal Data
Before you can clean, plot or model a column, you have to know what kind of values it holds. The kind decides which summary makes sense (a mean of postcodes is meaningless), which plot to draw, and how the column must be turned into numbers for a model. This lesson covers the four types found in almost every table; the next lessons cover time series, text, images, audio, video and graphs.
The four tabular types
| Type | Values | Example columns | Meaningful operations |
|---|---|---|---|
| Numerical, continuous | any real number in a range | weight in kg, temperature, price | order, difference, mean, standard deviation |
| Numerical, discrete | counts, whole numbers | number of children, page views | order, difference, mean |
| Categorical (nominal) | a fixed set of names with no order | city, blood type, product colour | count, mode, equality only |
| Binary | exactly two values | smoker yes/no, spam/not spam, churned | count, share (the mean of a 0/1 column is a proportion) |
| Ordinal | categories with a natural order but no fixed distance | T-shirt size S < M < L, survey answer "disagree" < "neutral" < "agree", pain level 1–5 | order, median, mode, but not mean (strictly) |
The measurement levels lesson of the Statistics course gives the classic names (nominal, ordinal, interval, ratio) for the same idea.
Two traps come up again and again:
- Numbers that are categories. A postcode, a product id, a phone number or a patient id is written with digits, but it is a name. Its mean is nonsense, and a model that treats it as a quantity will think that postcode 70000 is "bigger" than 10000.
- Ordinal values stored as text. If "S", "M", "L" are plain strings, sorting gives "L" < "M" < "S" (alphabetical), and the order is lost.
What the types look like in pandas
pandas stores each column with a dtype. The dtype is a storage decision, not a meaning: pandas cannot know that zip_code is a category. You tell it.
import pandas as pd
shop = pd.DataFrame({
"order_id": [5001, 5002, 5003, 5004, 5005, 5006],
"zip_code": [10115, 70173, 10115, 80331, 50667, 70173],
"items": [1, 3, 2, 1, 5, 2],
"total_eur": [19.99, 84.50, 42.00, 9.95, 130.25, 55.10],
"colour": ["red", "blue", "red", "green", "blue", "blue"],
"size": ["M", "L", "S", "M", "XL", "S"],
"gift_wrap": [False, True, False, False, True, False],
})
print(shop.dtypes)
print()
print("mean zip code (meaningless):", shop["zip_code"].mean())
print("sorted sizes as text:", sorted(shop["size"].unique()))order_id int64
zip_code int64
items int64
total_eur float64
colour object
size object
gift_wrap bool
dtype: object
mean zip code (meaningless): 48595.666666666664
sorted sizes as text: ['L', 'M', 'S', 'XL']
pandas guessed int64 for the ids and the zip code, float64 for the money, bool for the yes/no column and object (Python strings) for the text. The mean zip code is a number that belongs to no place, and the text sort gives L, M, S, XL, alphabetical instead of by size. Fix both by declaring the meaning:
import pandas as pd
shop = pd.DataFrame({
"zip_code": [10115, 70173, 10115, 80331, 50667, 70173],
"colour": ["red", "blue", "red", "green", "blue", "blue"],
"size": ["M", "L", "S", "M", "XL", "S"],
"gift_wrap": [False, True, False, False, True, False],
})
shop["zip_code"] = shop["zip_code"].astype(str).astype("category")
shop["colour"] = shop["colour"].astype("category")
shop["size"] = pd.Categorical(shop["size"], categories=["S", "M", "L", "XL"], ordered=True)
print(shop.dtypes)
print()
print("sizes in order:", list(shop["size"].sort_values()))
print("orders of size M or larger:", int((shop["size"] >= "M").sum()))
print("share with gift wrap:", shop["gift_wrap"].mean())
print("most common colour:", shop["colour"].mode()[0])zip_code category
colour category
size category
gift_wrap bool
dtype: object
sizes in order: ['S', 'S', 'M', 'M', 'L', 'XL']
orders of size M or larger: 4
share with gift wrap: 0.3333333333333333
most common colour: blue
An ordered categorical knows that S < M < L < XL, so comparisons such as >= "M" work. The mean of a boolean column is the share of True values, the natural summary for binary data. For nominal data, the mode (most common value) is the summary that makes sense.
How a model sees each type
Models need numbers. The type decides the encoding, which Data Preparation covers in depth. In short:
| Type | Usual encoding | Why |
|---|---|---|
| continuous / discrete | use as is, often scaled | already a quantity |
| binary | 0 and 1 | one column carries all the information |
| ordinal | integer ranks 0, 1, 2, … in the right order | keeps the order |
| nominal | one-hot: one 0/1 column per category | no fake order between categories |
import pandas as pd
df = pd.DataFrame({
"colour": ["red", "blue", "red", "green"],
"size": ["M", "L", "S", "M"],
"gift_wrap": [False, True, False, False],
})
size_rank = {"S": 0, "M": 1, "L": 2, "XL": 3}
encoded = pd.DataFrame({
"size_rank": df["size"].map(size_rank),
"gift_wrap": df["gift_wrap"].astype(int),
})
encoded = encoded.join(pd.get_dummies(df["colour"], prefix="colour", dtype=int))
print(encoded) size_rank gift_wrap colour_blue colour_green colour_red
0 1 0 0 0 1
1 2 1 1 0 0
2 0 0 0 0 1
3 1 0 0 1 0
Encoding colour as 0, 1, 2 instead would tell a linear model that green is "between" blue and red, an order that does not exist.
Detecting types automatically, with care
A quick heuristic helps when a table has many columns: a numeric column with only a handful of distinct values is often a code or a category, and a text column with few distinct values is a category.
import pandas as pd
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True).frame
for col in ["alcohol", "magnesium", "proline", "target"]:
s = wine[col]
kind = "probably categorical" if s.nunique() <= 10 else "probably numerical"
print(f"{col:10} dtype={str(s.dtype):8} distinct={s.nunique():3} -> {kind}")alcohol dtype=float64 distinct=126 -> probably numerical
magnesium dtype=float64 distinct= 53 -> probably numerical
proline dtype=float64 distinct=121 -> probably numerical
target dtype=int32 distinct= 3 -> probably categorical
target holds the three wine cultivars coded 0, 1, 2, so it is a category even though its dtype is an integer. Heuristics are a starting point; the dataset's documentation (its data dictionary) is the real answer.
Pitfalls
- Averaging codes: ids, postcodes and category numbers are names, not quantities.
- Losing an order: keep ordinal columns as ordered categoricals or explicit ranks.
- Inventing an order: never encode nominal categories as 0, 1, 2 for a linear or distance-based model.
- Trusting the dtype:
int64means "stored as integers", not "is a quantity". A column of"1","2","3"strings isobjectbut may be numeric.
Practice
- Classify each column:
blood_type,heart_rate,num_visits,satisfaction(1 = very unhappy … 5 = very happy),is_insured,employee_id.
Answer
blood_type nominal categorical; heart_rate continuous numerical (measured, though often rounded); num_visits discrete numerical; satisfaction ordinal; is_insured binary; employee_id nominal (an identifier, never a quantity).
- A survey stores answers as
"agree","neutral","disagree". Write the line that turns the columnansinto an ordered categorical.
Answer
df["ans"] = pd.Categorical(df["ans"], categories=["disagree", "neutral", "agree"], ordered=True)
Test yourself
Which column is ordinal?
- Postcode
- Shoe colour
- Education level: primary, secondary, university
- Body temperature in °C
What is the mean of a 0/1 (binary) column?
- Always 0.5
- The share of rows that are 1
- The most common value
- It is undefined
Why is one-hot encoding preferred over 0, 1, 2 codes for a nominal column like colour?
- It uses less memory
- It avoids inventing an order and distances between categories
- It is required by pandas
- It removes missing values
pandas reads a zip_code column as int64. What should you conclude?
- It is a numerical feature
- Nothing about its meaning: the dtype is only how it is stored
- It must be ordinal
- It contains no missing values, so it is clean