Overview
Data typed by people or exported by different systems spells one fact in many ways: NY, ny and N.Y. for one state, 1,200.50 and 1200.5 for one number, 03/04/2024 and 2024-04-03 for one date. A model sees each spelling as a different value. Standardising means choosing one written form for each kind of value and converting everything to it. Each method here takes one raw value and returns its canonical form: cleaned text, a float, a date string in one pattern, or a boolean.
A short history
Format standardisation is a practice from data entry and database work, not the invention of one person. It grew with data warehousing in the 1990s, when extract, transform, load jobs had to combine systems that wrote dates, units and codes differently. Shared standards support it: ISO 8601 for dates and times was first published in 1988, and Unicode defines normal forms for text.
How it works
- Decide the kind of each column: text, number, date or bool.
- Check for missing first. None, NaN and any spelling in missing_tokens (such as n/a or an empty string) become one null value.
- For text, clean_text trims, collapses runs of whitespace and sets the letter case. map_value then looks the cleaned text up in a mapping from spellings to a canonical category.
- For numbers, to_number strips currency signs and thousands separators, reads brackets as a negative sign and a percent sign as division by 100, and returns a float.
- For dates, to_date tries each pattern in date_formats in order and writes the first match in the date_output pattern.
- For booleans, to_bool compares the lower-cased text with true_tokens and false_tokens.
- A value that cannot be read either raises an error or becomes null, as the errors setting says. standardize applies the chosen conversion to a whole column.
Watch out for
- A date such as 03/04/2024 fits both day-first and month-first patterns. The first pattern in date_formats wins, so a wrong order shifts dates silently and without any error.
- With decimal_comma off, the text 1.234,5 loses its comma and is read as 1.2345. A wrong locale setting changes numbers by factors of a thousand.
- Setting errors to null hides unreadable values as missing ones. Count the nulls before and after, or real format problems vanish into the imputation step.
- The token 1 is read as true and 0 as false, so running to_bool on a numeric column quietly turns it into flags.
- This template covers common formats with fixed rules. It does no fuzzy matching, so a misspelling such as Nwe York needs an entry in the mapping.
Use cases
When to use it
Right after loading raw data and before encoding, deduplicating or imputing. Those later steps all assume that equal things are written equally.
In industry
- Healthcare
- Hospitals convert lab results from different instruments into the same units and codes before records are combined or analysed.
- E-commerce
- Marketplaces normalise seller-supplied attributes such as sizes, colours and country names so that product filters work.
- Banking
- Banks standardise dates, currency codes and customer names across internal systems for reporting and for matching transactions.
Choosing it: what must hold
- A canonical form chosen for each type of value: one date layout, one unit, one spelling per category.
- A mapping or parsing rule from every variant seen in the data to that form.
- A plan for values that match no rule: flag them or set them to missing, do not guess.
- Knowledge of ambiguous cases, such as whether 03/04 means March or April, from the data source.
When to choose something else
| If | Use instead |
|---|---|
| Variants are typos with no fixed pattern | Fuzzy matching against a list of valid values |
| After standardising, some values are still blank or unparseable | Missing value handling |
| The column is clean text categories that only need to become numbers | Categorical encoding |
Math foundations
Canonical form
A cleaning function should be idempotent: cleaning a value that is already clean changes nothing. This is a quick test for any cleaning rule, and clean_text satisfies it.
Spellings form classes
Two raw spellings count as the same value exactly when they clean to the same result. The number of categories a model sees is the number of these classes, not the number of raw spellings.
Percent and bracket rules
to_number reads a trailing percent sign as division by 100 and accounting brackets as a negative amount. These are the only two arithmetic rules it applies.
Symbols
- raw values as they appear in the data
- the cleaning function for one kind of value
- the relation of being the same value after cleaning
- a number written as a percentage
- a positive amount written inside accounting brackets
Worked by hand
Read three raw strings with to_number and the default settings: (1,200.50) in brackets, 45% and 1.234,5 written with a decimal comma.
The first two are read as intended. The third is wrong by a factor of 1000 because the comma was treated as a thousands separator. Setting decimal_comma to true gives 1234.5.
Visual example
Loading the example.
Try this
- Click the row 1.234,5 and read the stages: the comma is removed and the answer is wrong by a factor of 1000. Then turn decimal_comma on.
- Click each stage of the diagram to see the text going in and coming out of it.
- Type your own value, such as (45%) or EUR 3,000, and follow it through.
Code sample
from impl import FormatStandardizer
from config import FormatStandardizerConfig
std = FormatStandardizer(FormatStandardizerConfig(case="lower"))
print(std.standardize([" New York", "N.Y.", "nyc"], "text", {"n.y.": "new york", "nyc": "new york"}))
# ['new york', 'new york', 'new york']
print(std.standardize(["$1,234.50", "45%", "(300)", "n/a"], "number")) # [1234.5, 0.45, -300.0, nan]
print(std.standardize(["2024-03-05", "05/03/2024", "5 Mar 2024"], "date")) # three times '2024-03-05'
print(std.standardize(["Yes", "N", "TRUE"], "bool")) # [True, False, True]Read the implementation (150 lines)
"""Standardise inconsistently written values: text, category spellings, numbers, dates and booleans.
Standard library and NumPy only. Each method takes one raw value (usually a string typed by a person or
exported by another system) and returns it in one canonical form, so that "N.Y.", " ny" and "New York" can
become one category, "$1,200.50" and "1200.5" one number, and "03/04/2024" and "2024-04-03" one date.
"""
from __future__ import annotations
import math
import re
from datetime import date, datetime
import numpy as np
try:
from .config import FormatStandardizerConfig
except ImportError: # run from the template's own folder
from config import FormatStandardizerConfig
_NUMBER_JUNK = re.compile(r"[\s$€£¥_]|usd|eur|gbp", re.IGNORECASE)
_NUMBER_OK = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
_KINDS = ("text", "number", "date", "bool")
class FormatStandardizer:
"""Turns raw values into canonical text, floats, ISO-style date strings and booleans."""
def __init__(self, config: FormatStandardizerConfig | None = None) -> None:
self.config = config or FormatStandardizerConfig()
def is_missing(self, value) -> bool:
"""True for None, NaN and any spelling listed in `missing_tokens`."""
if value is None:
return True
if isinstance(value, (float, np.floating)) and math.isnan(value):
return True
return isinstance(value, str) and value.strip().lower() in self.config.missing_tokens
def _fail(self, value, what: str, null):
"""Raise or return the null value for an unreadable input, as `errors` says."""
if self.config.errors == "raise":
raise ValueError(f"cannot read {value!r} as {what}")
return null
def clean_text(self, value) -> str | None:
"""Trim, collapse whitespace and set the letter case. Missing values give None."""
if self.is_missing(value):
return None
text = str(value)
if self.config.collapse_whitespace:
text = " ".join(text.split())
if self.config.case == "lower":
return text.lower()
if self.config.case == "upper":
return text.upper()
if self.config.case == "title":
return text.title()
return text
def map_value(self, value, mapping: dict, default=None):
"""Replace a spelling by its canonical value.
mapping: {spelling: canonical}. Both the keys and the value are cleaned with `clean_text` before the
lookup, so the mapping does not have to list case or spacing variants. A value that is not in the
mapping is returned cleaned, or as `default` when one is given.
"""
cleaned = self.clean_text(value)
if cleaned is None:
return None
table = {self.clean_text(k): v for k, v in mapping.items()}
if cleaned in table:
return table[cleaned]
return cleaned if default is None else default
def to_number(self, value) -> float:
"""Read a number written with currency signs, thousands separators, a percent sign or brackets.
"$1,234.50" gives 1234.5, "45%" gives 0.45, "(300)" gives -300.0 (accounting style). Missing gives NaN.
"""
if self.is_missing(value):
return float("nan")
if isinstance(value, bool):
return float(value)
if isinstance(value, (int, float, np.integer, np.floating)):
return float(value)
text = _NUMBER_JUNK.sub("", str(value))
negative = text.startswith("(") and text.endswith(")")
if negative:
text = text[1:-1]
percent = text.endswith("%")
if percent:
text = text[:-1]
if self.config.decimal_comma:
text = text.replace(".", "").replace(",", ".")
else:
text = text.replace(",", "")
if not _NUMBER_OK.match(text):
return self._fail(value, "a number", float("nan"))
number = float(text)
if percent:
number /= 100.0
return -number if negative else number
def to_date(self, value) -> str | None:
"""Read a date in any of `date_formats` and write it as `date_output`. Missing gives None."""
if self.is_missing(value):
return None
if isinstance(value, (datetime, date)):
return value.strftime(self.config.date_output)
text = " ".join(str(value).split())
for pattern in self.config.date_formats:
try:
return datetime.strptime(text, pattern).strftime(self.config.date_output)
except ValueError:
continue
return self._fail(value, "a date", None)
def to_bool(self, value) -> bool | None:
"""Read yes/no style values using `true_tokens` and `false_tokens`. Missing gives None."""
if self.is_missing(value):
return None
if isinstance(value, (bool, np.bool_)):
return bool(value)
text = str(value).strip().lower()
if isinstance(value, (int, float, np.integer, np.floating)) and float(value) in (0.0, 1.0):
text = str(int(value))
if text in self.config.true_tokens:
return True
if text in self.config.false_tokens:
return False
return self._fail(value, "a boolean", None)
def standardize(self, values, kind: str = "text", mapping: dict | None = None) -> list:
"""Standardise a whole column.
values: iterable of raw values. kind: "text", "number", "date" or "bool". mapping: optional
{spelling: canonical} applied to text. Returns a list of the same length.
"""
if kind not in _KINDS:
raise ValueError(f"kind must be one of {_KINDS}, got {kind!r}")
if kind == "text":
if mapping:
return [self.map_value(v, mapping) for v in values]
return [self.clean_text(v) for v in values]
convert = {"number": self.to_number, "date": self.to_date, "bool": self.to_bool}[kind]
return [convert(v) for v in values]
def to_float_array(self, values) -> np.ndarray:
"""Column of raw numbers as a float array, shape (n,), NaN where missing."""
return np.array([self.to_number(v) for v in values], dtype=float)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Make a column of twelve messy strings: states spelled several ways, amounts with currency words and brackets, and dates in three layouts. Run FormatStandardizer.standardize with kind set to text and a mapping, then with kind number and kind date. Set errors to null in the FormatStandardizerConfig and count the nulls. Then reorder date_formats and list which dates changed.
Check on learning
- A column holds dates from a United States office and a European office in the same slash layout. Can any ordering of date_formats read all of them correctly? What else would you need?
A way to think about it
Take 03/04/2024 from each office. The text is identical, so think about what information outside the cell could tell them apart.
- Why is idempotence a useful property to test for a cleaning function, and what would it mean in practice if it failed?
A way to think about it
Imagine a pipeline that is run twice on the same table, or run on a table that was partly cleaned already. What should happen to a clean value?
- After standardising, a category column drops from 40 distinct values to 9. A colleague worries that information was lost. How would you check whether that is true?
A way to think about it
Compare the groups of raw spellings that merged. Ask whether any merged group joins values that the task needs to tell apart.
- When is raising an error on an unreadable value better than turning it into null, and when is the reverse true?
A way to think about it
Think about a one-off exploration of a file against a nightly job, and about what a rising share of nulls would tell you about the source.