TExcelTAD

Duplicates and Data Types

Data for ML taught you to find duplicate rows and wrongly typed columns. This lesson is about fixing them: deciding which copy of a record to keep, and turning text that only looks like numbers, booleans or categories into columns with the right type. Both fixes come first in every cleaning script, because every later step (imputation, scaling, encoding) assumes one row per real-world entity and columns that hold what their names say.

Duplicates: three kinds, three decisions

Kind Example Usual decision
Exact duplicate the same order exported twice drop all but one copy
Key duplicate with conflicting values customer 17 appears with two different emails keep one by a stated rule (latest update, most complete, trusted source)
Near duplicate "Ann Lee" and "ann lee " with the same birth date normalise first, then treat as a key duplicate

Exact duplicates are cheap to fix. The other two need a rule you can write down, because "I picked the one that looked right" cannot be repeated on next month's data.

python · try it yourself
import pandas as pd

orders = pd.DataFrame({
    "order_id":  [1001, 1002, 1002, 1003, 1004, 1004, 1005],
    "customer":  ["Ann Lee", "Bo Chen", "Bo Chen", "ann  lee ", "Dev Rao", "Dev Rao", "Eva Ruiz"],
    "amount":    [25.0, 40.0, 40.0, 25.0, 12.5, 13.0, 60.0],
    "updated":   ["2026-03-01", "2026-03-02", "2026-03-02", "2026-03-01",
                  "2026-03-03", "2026-03-05", "2026-03-04"],
})

exact = orders.duplicated()
print("exact duplicate rows:", exact.sum())
step1 = orders[~exact]

# Key duplicates: same order_id, different values. Rule: keep the latest update.
key_dupes = step1[step1.duplicated("order_id", keep=False)]
print("conflicting copies of order 1004:")
print(key_dupes[["order_id", "amount", "updated"]].to_string(index=False))
step2 = (step1.sort_values(["order_id", "updated"])
              .drop_duplicates("order_id", keep="last"))

# Near duplicates: normalise the name before comparing.
step2 = step2.assign(customer_key=step2["customer"].str.lower().str.split().str.join(" "))
print("rows per normalised customer:", step2["customer_key"].value_counts().to_dict())
print("rows: ", len(orders), "->", len(step1), "->", len(step2))
exact duplicate rows: 1
conflicting copies of order 1004:
 order_id  amount    updated
     1004    12.5 2026-03-03
     1004    13.0 2026-03-05
rows per normalised customer: {'ann lee': 2, 'bo chen': 1, 'dev rao': 1, 'eva ruiz': 1}
rows:  7 -> 6 -> 5

The cleaning went from 7 rows to 6 (one exact copy of order 1002 removed) and then to 5 (the older, 12.50 copy of order 1004 replaced by the update of 2026-03-05). Orders 1001 and 1003 now share the normalised customer key ann lee. They have different order ids, so they are two orders by one customer, not duplicates; the key matters later, when you split by customer so that one person's orders never sit on both sides of a split.

Note: Never deduplicate on every column except the id. Two genuinely different patients can share age, sex and diagnosis. Decide what identifies an entity (an id, or a combination such as name + birth date + postcode) and deduplicate on that.

Duplicates and leakage

Duplicates across a split are worse than duplicates inside one: a test row that also sits in the training set is "predicted" from memory, and the score goes up for no good reason. So deduplicate before splitting, and for near duplicates (the same photo resized, the same sentence with different punctuation) use a group split so all copies land on one side.

Data types: make every column say what it holds

CSV files carry no types. pandas guesses, and a single stray value turns a numeric column into object (strings). The typical culprits:

Symptom Cause Fix
price is object "1,299.00", "$12", "12 EUR" strip symbols, then pd.to_numeric(..., errors="coerce")
age is float64 one missing value (NumPy integers have no NaN) nullable Int64
active holds "yes", "Y", "true", 1 several systems wrote it explicit mapping to boolean
zip lost its leading zeros read as a number read as str (dtype={"zip": str})
plan repeats a few strings free text type category with the allowed values

errors="coerce" turns anything that will not parse into NaN. That is what you want, but only if you count what was coerced, otherwise you silently create missing values:

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

raw = pd.DataFrame({
    "price":  ["1,299.00", "$12", "45.5", "n/a", "12 EUR", "7"],
    "age":    ["34", "51", "", "29", "47", "62"],
    "active": ["yes", "Y", "false", "1", "no", "TRUE"],
    "zip":    ["02134", "10001", "94105", "00501", "60601", "73301"],
    "plan":   ["basic", "pro", "Pro", "basic", "team", "pro"],
})
print(raw.dtypes.astype(str).to_dict())

clean = pd.DataFrame(index=raw.index)
price_text = raw["price"].str.replace(r"[,$]|EUR", "", regex=True).str.strip()
clean["price"] = pd.to_numeric(price_text, errors="coerce")
print("price values that did not parse:", raw["price"][clean["price"].isna()].tolist())

clean["age"] = pd.to_numeric(raw["age"].replace("", np.nan)).astype("Int64")

truth = {"yes": True, "y": True, "true": True, "1": True,
         "no": False, "n": False, "false": False, "0": False}
clean["active"] = raw["active"].str.lower().map(truth).astype("boolean")
unmapped = raw["active"][clean["active"].isna()]
print("active values not in the mapping:", unmapped.tolist())

clean["zip"] = raw["zip"].astype("string")
clean["plan"] = pd.Categorical(raw["plan"].str.lower(), categories=["basic", "pro", "team"])
print(clean.dtypes.astype(str).to_dict())
print(clean.to_string())
{'price': 'object', 'age': 'object', 'active': 'object', 'zip': 'object', 'plan': 'object'}
price values that did not parse: ['n/a']
active values not in the mapping: []
{'price': 'float64', 'age': 'Int64', 'active': 'boolean', 'zip': 'string', 'plan': 'category'}
    price   age  active    zip   plan
0  1299.0    34    True  02134  basic
1    12.0    51    True  10001    pro
2    45.5  <NA>   False  94105    pro
3     NaN    29    True  00501  basic
4    12.0    47   False  60601   team
5     7.0    62    True  73301    pro

Every column started as object. After cleaning, price is a float with one honest NaN (the "n/a" that really is unknown), age is a nullable integer with <NA> instead of a float, active is a true boolean, the ZIP codes kept their leading zeros, and plan is a categorical with exactly three allowed values, so "Pro" and "pro" became one category. The mapping for active is explicit: a new spelling such as "maybe" would show up as unmapped instead of being guessed.

Pitfalls

  • Dropping duplicates with keep="first" without sorting: "first" then means "whatever order the file had". Sort by the column your rule uses.
  • Coercing without counting: errors="coerce" can turn half a column into NaN because of a thousands separator. Always print what failed to parse.
  • Using astype(int) on a column with missing values: it fails, or (after fillna(0)) invents zeros. Use Int64.
  • Identifiers as numbers: ZIP codes, phone numbers and product codes are labels. Arithmetic on them is meaningless, and a model would treat 10001 as "bigger" than 02134.
  • Cleaning after the split in two different ways: cleaning rules (types, spellings, dedup rules) are fixed in advance and do not learn from the data, so they may run on the full dataset before the split. Anything that learns from the data (a median, a category frequency) must be fitted on the training part only; see The Leakage Rules.

Practice

  1. A sensor log has rows (device, timestamp, value). Some rows appear twice with the same device and timestamp but different values. What rule could you use, and what should you record?
Answer

There is no single right rule; it must fit the source. Options: keep the later write (if the log has an ingestion time), average the two values (if both are valid readings), or drop both (if a conflict means the device glitched). Record the rule, the number of affected keys and a few examples in the cleaning log (Corrupted Files and the Cleaning Log).

  1. pd.to_numeric(df["weight"], errors="coerce") produced 312 NaN values out of 5,000. What do you do before moving on?
Answer

Look at the original strings that failed: df["weight"][parsed.isna() & df["weight"].notna()].value_counts(). Typical causes are units ("72 kg"), decimal commas ("72,5") or placeholders. Fix the patterns you understand, and only leave real unknowns as NaN.

Test yourself

Order 1004 appears twice with amounts 12.50 and 13.00 and update dates 2026-03-03 and 2026-03-05. The rule is 'keep the latest update'. What must happen before drop_duplicates('order_id', keep='last')?

  1. Nothing
  2. Sort by order_id and update date
  3. Convert amount to integers
  4. Reset the index

Why should a column of ZIP codes be read as text?

  1. Text is faster
  2. As numbers they lose leading zeros and suggest an order and arithmetic that mean nothing
  3. pandas cannot store integers
  4. Models need strings

An age column has one missing value. Which dtype keeps integers and the missing value?

  1. int64
  2. float64
  3. Int64 (nullable)
  4. object

Why deduplicate before the train/test split?

  1. It is faster
  2. A row in both sets lets the model 'predict' test rows it has memorised, inflating the score
  3. Splitting needs unique indexes
  4. Duplicates change the column types