Categorical data

On this page 7

Categorical data is data whose values are labels drawn from a limited set of groups, such as country, blood type, product category or customer segment, rather than measured quantities. Among Data fundamentals, it is one of the two basic families of variables, alongside numeric or quantitative data, and the distinction determines which statistics, charts and machine learning techniques are valid.

A value of categorical data tells which group an observation belongs to, not how much of something it has. Even when categories are stored as numbers, such as postal codes or status codes 1, 2 and 3, arithmetic on them is usually meaningless: the average of three postal codes describes nothing real.

How categorical data is structured

A categorical variable has a finite set of possible values called levels or categories. Each observation takes exactly one level in the simplest case, and the full list of levels forms the variable’s domain. Good categorical design makes the levels mutually exclusive and collectively exhaustive, often by adding an explicit “other” or “unknown” level.

The number of distinct levels is called cardinality. A variable such as sex recorded at birth has low cardinality, while product SKU or user ID can have thousands to millions of levels, which changes how the data must be stored, summarized and modeled.

CardinalityTypical number of levelsExamplesMain concern
Binary2Churned or retained, yes or noClass imbalance
Low3 to about 20Region, payment method, plan tierFew concerns, easy to chart
MediumAbout 20 to a few hundredCountry, product categorySparse cells in cross-tabulations
HighThousands or moreZIP code, SKU, merchant IDEncoding size and overfitting
Cardinality levels of categorical variables

Nominal and ordinal categorical data

Categorical data divides into nominal and ordinal types. Nominal categories have no natural order: eye color or department name can be listed in any sequence. Ordinal categories have a meaningful order but unequal or unknown spacing, such as satisfaction ratings from very dissatisfied to very satisfied, or education level.

The distinction matters because ordinal data supports medians and percentiles while nominal data supports only counts, proportions and the mode. Treating a five-point rating as an interval number and averaging it is common in practice, but it assumes equal distances between levels, which respondents rarely guarantee.

Measurement levelExampleValid summariesFamily
NominalBrowser typeCounts, proportions, modeCategorical
OrdinalCustomer satisfaction ratingMode, median, percentilesCategorical
IntervalTemperature in CelsiusMean, standard deviationNumeric
RatioOrder value in dollarsAll of the above plus ratiosNumeric
Measurement levels and the operations they support

Categorical data is closely related to qualitative data but not identical. Qualitative data also covers free text and interview notes; categorical data is the coded, structured form in which each record is assigned to a defined group.

Storing and encoding categorical data

In databases and files, categorical data is usually stored as text labels or integer codes with a lookup table. Analytical formats and libraries offer dedicated types, such as the pandas category dtype, the R factor and dictionary encoding in Apache Parquet and Apache Arrow, which store each distinct label once and reference it by a small integer. This can reduce memory use substantially for repetitive columns.

Most statistical models and machine learning algorithms require numbers, so categories must be encoded before training. The choice of encoding is one of the most consequential preprocessing decisions.

EncodingHow it worksBest suited forMain risk
One-hot encodingOne binary column per levelNominal data with low cardinalityVery wide tables for many levels
Ordinal encodingIntegers that follow the orderOrdinal dataImplies order where none exists
Target encodingReplaces a level with an outcome statisticHigh-cardinality featuresTarget leakage without cross-validation
Frequency encodingReplaces a level with its countTree-based modelsDifferent levels can collide
Feature hashingMaps levels into a fixed number of bucketsVery large or open-ended domainsHash collisions reduce interpretability
Learned embeddingsTrains dense vectors per levelNeural networks with many levelsNeeds enough data per level
Common encoding methods for categorical data

Analyzing and visualizing categorical data

The basic analysis of categorical data is the frequency table, which counts observations per level, and the contingency table, which cross-tabulates two categorical variables. Associations between them are commonly tested with the chi-square test of independence, or with Fisher’s exact test when expected cell counts are small.

For visualization, bar charts are the default choice because they compare counts or proportions on a common scale. Stacked or grouped bars and mosaic plots show two variables at once. Pie charts work only for a small number of parts of one whole; with more than about five slices, comparisons become unreliable.

  • Sort nominal bars by frequency, but keep ordinal bars in their natural order.
  • Group rare levels into an explicit “other” bucket and state the threshold used.
  • Report proportions together with counts, so that small groups are not overinterpreted.

Common data quality problems with categories

Categorical columns are a frequent source of data quality defects, because labels are often typed by people or merged from systems with different code lists. Small inconsistencies split one real group into several apparent groups and distort counts.

SymptomCauseFix
“USA”, “U.S.” and “United States” counted separatelyFree-text entry without a controlled vocabularyMap to a standard code list such as ISO 3166
New level crashes a trained modelLevel unseen during trainingReserve an unknown level in the encoder
Model scores unrealistically wellTarget encoding computed on the full datasetCompute encodings inside cross-validation folds
Blank and “N/A” treated differentlyInconsistent missing-value markersNormalize missing values to one representation
Chart dominated by tiny barsLong tail of rare levelsCollapse rare levels into a labeled group
Typical problems in categorical columns

The strongest prevention is a controlled vocabulary enforced at entry, for example a drop-down list or a reference table with a foreign key constraint, documented in the dataset’s metadata so that every consumer interprets the codes the same way.

In everyday language

Categorical data is information that sorts things into groups instead of measuring them. Your favorite color, the city you live in or the size of a T-shirt you order are all categories.

You can count how many people chose each group, and with sizes like small, medium and large you can put the groups in order. What you cannot sensibly do is add or average the groups. Categories answer “which kind”, not “how much”.

Seen in the real world

An online retailer wants to predict which orders will be returned. Its dataset contains numeric fields such as order value and categorical fields such as payment method with 6 levels, shipping region with 12 levels and product SKU with about 40,000 levels.

The analytics team one-hot encodes payment method and region, but uses target encoding computed within cross-validation folds for SKU, because one-hot encoding would create tens of thousands of sparse columns. During cleaning they discover that the region field contains 19 distinct spellings for its 12 real regions and map them to a standard code list.

The resulting model identifies a small group of SKUs in two clothing categories that account for a large share of returns. The retailer adds size guidance to those product pages and sees return rates in those categories decline over the following quarter.