TExcelTAD
Home › Data for ML: Types, Formats, Sources & Quality › Data Consistency: Units, Formats, Ranges and Names

Data Consistency: Units, Formats, Ranges and Names

A dataset is consistent when the same thing is always recorded the same way: one unit per column, one format per date, one spelling per category, values inside their valid ranges, and columns that agree with each other. Inconsistency appears whenever data comes from several people, systems, countries or time periods, which is to say almost always. It is dangerous because each value on its own looks fine: 154 is a perfectly good weight, 03/04/2026 a perfectly good date, "HCMC" a perfectly good city. Only the comparison with the rest of the column reveals the problem.

Names and categories

The same category written several ways splits one class into many:

python · try it yourself
import pandas as pd

cities = pd.Series(["Ho Chi Minh City", "HCMC", "ho chi minh city", "TP.HCM", "Hanoi",
                    "Ha Noi", "hanoi ", "Hà Nội", "Da Nang", "Danang", "Hue", "Saigon"])
print("distinct as written:", cities.nunique())

def key(s):
    return (s.str.strip().str.lower()
             .str.normalize("NFKD").str.encode("ascii", "ignore").str.decode("ascii")   # drop accents
             .str.replace(r"[^a-z]", "", regex=True))

canonical = {
    "hochiminhcity": "Ho Chi Minh City", "hcmc": "Ho Chi Minh City", "tphcm": "Ho Chi Minh City",
    "saigon": "Ho Chi Minh City", "hanoi": "Hanoi", "danang": "Da Nang", "hue": "Hue",
}
k = key(cities)
clean = k.map(canonical)
print("keys:", sorted(k.unique()))
print("unmapped:", sorted(k[clean.isna()].unique()))
print(clean.value_counts())
distinct as written: 12
keys: ['danang', 'hanoi', 'hcmc', 'hochiminhcity', 'hue', 'saigon', 'tphcm']
unmapped: []
Ho Chi Minh City    5
Hanoi               4
Da Nang             2
Hue                 1
Name: count, dtype: int64

Two steps do most of the work: a mechanical normalisation (trim, lower-case, remove accents and punctuation) that merges trivial variants, and a reviewed mapping table for the real synonyms (HCMC, TP.HCM, Saigon). Print the unmapped keys every time new data arrives: they are the new variants someone must add to the table. Keep the table in version control, next to the code.

Units

A unit mix-up is a consistency problem that statistics alone can miss: a weight column with some values in pounds looks like a heavier group of people. Two clues help: the distribution has a second bump at about the conversion factor times the first, and the value disagrees with related columns. Here the body-mass index computed from height flags the rows recorded in pounds:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
n = 12
height_cm = np.round(rng.normal(168, 9, n))
weight_kg = np.round(22 * (height_cm / 100) ** 2 + rng.normal(0, 6, n), 1)
weight = weight_kg.copy()
lb_rows = [2, 7, 10]
weight[lb_rows] = np.round(weight_kg[lb_rows] * 2.20462, 1)           # recorded in pounds

df = pd.DataFrame({"height_cm": height_cm, "weight": weight})
df["bmi_if_kg"] = (df["weight"] / (df["height_cm"] / 100) ** 2).round(1)
df["suspect_lb"] = df["bmi_if_kg"] > 45
df["weight_kg"] = np.where(df["suspect_lb"], (df["weight"] / 2.20462).round(1), df["weight"])
print(df)
print("rows flagged:", df.index[df["suspect_lb"]].tolist(), "| really in pounds:", lb_rows)
    height_cm  weight  bmi_if_kg  suspect_lb  weight_kg
0       169.0    48.9       17.1       False       48.9
1       167.0    60.0       21.5       False       60.0
2       174.0   130.3       43.0       False      130.3
3       169.0    58.4       20.4       False       58.4
4       163.0    55.2       20.8       False       55.2
5       171.0    62.4       21.3       False       62.4
6       180.0    73.7       22.7       False       73.7
7       177.0   165.8       52.9        True       75.2
8       162.0    57.0       21.7       False       57.0
9       157.0    62.4       25.3       False       62.4
10      162.0   118.4       45.1        True       53.7
11      168.0    64.2       22.7       False       64.2
rows flagged: [7, 10] | really in pounds: [2, 7, 10]

A BMI above 45 is rare. The rule finds two of the three rows recorded in pounds, but misses row 2: a light person (59 kg) recorded as 130.3 lb gives a BMI of 43.0, high but possible, so it stays below the threshold. Lowering the threshold would start flagging real patients with severe obesity. No single cross-check catches everything; combine it with other evidence, above all where each row came from (one clinic, device or form version usually explains a whole group of pound values), and review converted rows instead of converting silently. Typical unit pairs to watch: kg and lb, cm and m or inches, °C and °F, km/h and m/s, seconds and milliseconds, currencies, and percentages stored as 0–100 in one source and 0–1 in another.

Formats: dates, numbers and codes

Dates are the worst offenders. 03/04/2026 is 3 April in Vietnam and most of Europe and 4 March in the United States. A day above 12 settles the question for one row; looking at all rows settles it for a source:

python · try it yourself
import pandas as pd

raw = pd.Series(["2026-04-03", "03/04/2026", "15/04/2026", "04/16/2026", "2026/04/20", "20260421", "April 22, 2026"])
formats = {"%Y-%m-%d": "ISO", "%d/%m/%Y": "day first", "%m/%d/%Y": "month first",
           "%Y/%m/%d": "year/month/day", "%Y%m%d": "compact", "%B %d, %Y": "written out"}
for value in raw:
    hits = [name for fmt, name in formats.items()
            if pd.notna(pd.to_datetime(value, format=fmt, errors="coerce"))]
    print(f"{value:15} parses as: {', '.join(hits)}")
2026-04-03      parses as: ISO
03/04/2026      parses as: day first, month first
15/04/2026      parses as: day first
04/16/2026      parses as: month first
2026/04/20      parses as: year/month/day
20260421        parses as: compact
April 22, 2026  parses as: written out

03/04/2026 parses under both the day-first and the month-first format, so it is ambiguous; 15/04/2026 can only be day-first and 04/16/2026 only month-first. If one source contains both kinds, it mixes conventions, and its ambiguous dates cannot be trusted without knowing where each row came from. The fix belongs at the source: store dates as ISO 8601 (2026-04-03), and parse every input with an explicit format, as in the CSV lesson.

The same care applies to numbers (1.234,56 vs 1,234.56), phone numbers (with or without country code), postcodes (leading zeros), booleans (yes/no, Y/N, 1/0, true/false) and identifiers (A-001 vs A001).

Ranges and cross-column rules

Some rules concern one column (a percentage between 0 and 100), others the relation between columns (an end date after the start date, a total equal to the sum of its parts). Writing them as a list of named checks gives a reusable validator, the core of tools such as Great Expectations, pandera or Pydantic:

python · try it yourself
import pandas as pd

orders = pd.DataFrame({
    "order_id": [1, 2, 3, 4, 5],
    "ordered":   pd.to_datetime(["2026-03-01", "2026-03-02", "2026-03-05", "2026-03-06", "2026-03-07"]),
    "delivered": pd.to_datetime(["2026-03-04", "2026-03-01", "2026-03-08", None, "2026-03-09"]),
    "items_total": [40.0, 25.0, 60.0, 15.0, 30.0],
    "shipping":    [5.0, 5.0, -5.0, 5.0, 0.0],
    "total":       [45.0, 30.0, 55.0, 20.0, 35.0],
    "discount_pct": [0, 10, 0, 150, 0],
})
checks = {
    "delivered before ordered": orders["delivered"] < orders["ordered"],
    "negative shipping":        orders["shipping"] < 0,
    "discount outside 0-100":   ~orders["discount_pct"].between(0, 100),
    "total != items + shipping": (orders["items_total"] + orders["shipping"] - orders["total"]).abs() > 0.005,
}
report = pd.DataFrame({name: mask for name, mask in checks.items()})
print(report.sum().rename("violations"))
print()
for name, mask in checks.items():
    if mask.any():
        print(f"{name}: order_id {orders.loc[mask, 'order_id'].tolist()}")
delivered before ordered     1
negative shipping            1
discount outside 0-100       1
total != items + shipping    1
Name: violations, dtype: int64

delivered before ordered: order_id [2]
negative shipping: order_id [3]
discount outside 0-100: order_id [4]
total != items + shipping: order_id [5]

Order 4 has no delivery date: a comparison with a missing date is simply false, so it is not reported as "delivered before ordered". That is the right behaviour here (missing values have their own check), but it is a reminder that every rule needs a decision about missing values. Order 5's total does not match its parts, maybe a fee nobody documented: a question for the data owner, not something to "fix" by guessing.

Pitfalls

  • Fixing by hand: every correction belongs in code (a mapping table, a conversion rule), so that it is reproducible and applies to next month's data too.
  • Converting without evidence: convert units only with a clear signal (a second column, a source with a known convention) and review the result.
  • Guessing ambiguous dates: find out the source's convention; do not let a parser guess per row.
  • Rules in people's heads: write range and cross-column rules down as executable checks and run them on every new batch.

Practice

  1. A temperature column has values between 15 and 35 for most rows and between 59 and 95 for some. What is likely going on, and how would you confirm it?
Answer

Some rows are in Fahrenheit (15–35 °C is 59–95 °F). Confirm by checking whether the high values come from one source, device or country, and whether converting them with °C = (°F − 32) × 5/9 makes them agree with nearby readings or other columns.

  1. Add a check to the order validator that flags orders whose delivery took more than 30 days.
Answer

"delivery over 30 days": (orders["delivered"] - orders["ordered"]).dt.days > 30. Missing delivery dates give NaN days, and the comparison is false for them.

Test yourself

The city column contains 'HCMC', 'TP.HCM' and 'Ho Chi Minh City'. What is the right fix?

  1. Leave them; the model will learn they are the same
  2. Normalise and map them to one canonical name with a reviewed mapping table
  3. Drop the column
  4. Keep only the most common spelling and delete the other rows

Which date is ambiguous between day-first and month-first formats?

  1. 2026-04-03
  2. 15/04/2026
  3. 03/04/2026
  4. 04/16/2026

Why can a unit mix-up hide from summary statistics?

  1. Units are not stored in files
  2. Each wrong value is plausible on its own; the problem appears only in the distribution or in relation to other columns
  3. pandas converts units automatically
  4. Statistics ignore large values

A rule says delivered >= ordered. For a row with a missing delivery date, the comparison…

  1. Raises an error
  2. Is false, so the row passes a 'delivered before ordered' check unnoticed
  3. Is true
  4. Deletes the row