protoneko's picture
Upload folder using huggingface_hub
61bb557 verified
Raw History Blame Contribute Delete
6.33 kB
"""
make_messy.py — Reproducibly generate a realistically messy 500-row CSV.
Simulates the kind of "customer orders" export you actually receive from a
legacy CRM: mixed date formats, duplicate rows, casing/whitespace noise,
sentinel nulls, and amounts that are text, not numbers.
Every row is produced from seed=42, so re-running the script always yields
the exact same file. The output is deliberately written with `csv` (no
pandas) so the mess is preserved verbatim — e.g. "NEW YORK" stays uppercase.
Usage:
python make_messy.py [output.csv]
"""
from __future__ import annotations
import csv
import datetime
import random
from pathlib import Path
SEED = 42
N_ROWS = 500
CITIES = [
"New York", "Chicago", "Houston", "Phoenix", "Philadelphia",
"San Antonio", "San Diego", "Dallas", "San Jose", "Austin",
"Jacksonville", "Columbus", "Charlotte", "San Francisco", "Seattle",
"Denver",
]
FIRST = ["James", "Mary", "John", "Patricia", "Robert", "Jennifer", "Michael",
"Linda", "David", "Elizabeth", "William", "Barbara", "Richard",
"Susan", "Joseph", "Jessica", "Thomas", "Sarah", "Charles", "Karen"]
LAST = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller",
"Davis", "Rodriguez", "Martinez", "Hernandez", "Lopez", "Gonzalez",
"Wilson", "Anderson", "Thomas", "Taylor", "Moore", "Jackson", "Martin"]
PAYMENTS = ["visa", "mastercard", "amex", "paypal", "bank_transfer"]
STATUSES = ["pending", "shipped", "delivered", "cancelled", "refunded"]
DATE_FORMATS = [
lambda d: d.strftime("%Y-%m-%d"), # 2024-03-01
lambda d: d.strftime("%m/%d/%Y"), # 03/01/2024
lambda d: d.strftime("%d/%m/%Y"), # 01/03/2024 (ambiguous!)
lambda d: d.strftime("%b %d, %Y"), # Mar 01, 2024
lambda d: d.strftime("%d-%b-%Y"), # 01-Mar-2024
lambda d: d.strftime("%Y/%m/%d"), # 2024/03/01
]
def main(out_path: Path) -> None:
rng = random.Random(SEED)
base_days = datetime.date(2024, 1, 1).toordinal()
rows: list[list[str]] = []
for i in range(1, N_ROWS + 1):
first, last = rng.choice(FIRST), rng.choice(LAST)
name = f"{first} {last}"
# casing + whitespace noise in names (20%)
r = rng.random()
if r < 0.06:
name = name.upper()
elif r < 0.12:
name = name.lower()
elif r < 0.16:
name = f" {name} "
elif r < 0.20:
name = name.replace(" ", " ")
email_base = f"{first}.{last}".lower()
domain = rng.choice(["gmail.com", "example.com", "outlook.com",
"yahoo.com", "company.org"])
email = f"{email_base}{rng.randint(1, 999)}@{domain}"
r = rng.random()
if r < 0.05:
email = email.upper()
elif r < 0.09:
email = f" {email} "
city = rng.choice(CITIES)
r = rng.random()
if r < 0.08:
city = city.upper()
elif r < 0.14:
city = city.lower()
elif r < 0.20:
city = f" {city} "
day = rng.randint(0, 364)
d = datetime.date.fromordinal(base_days + day)
fmt = rng.choice(DATE_FORMATS)
order_date = fmt(d)
qty = rng.randint(1, 12)
quantity = str(qty)
if rng.random() < 0.05:
quantity = f"{qty}.0" # float-string where int wanted
if rng.random() < 0.04:
quantity = f" {quantity}" # stray space
unit_price = round(rng.uniform(5.0, 500.0), 2)
if rng.random() < 0.10:
unit_price_s = f"${unit_price:,.2f}" # $1,234.56 as text
else:
unit_price_s = f"{unit_price:.2f}"
total = round(unit_price * qty, 2)
r = rng.random()
if r < 0.08:
total_s = f"${total:,.2f}"
elif r < 0.12:
total_s = f"({total:,.2f})" # accounting negatives-as-parens
# (kept positive here but formatted like a credit)
else:
total_s = f"{total:.2f}"
payment = rng.choice(PAYMENTS)
if rng.random() < 0.06:
payment = payment.upper()
if rng.random() < 0.05:
payment = f" {payment} "
status = rng.choice(STATUSES)
r = rng.random()
if r < 0.07:
status = status.upper()
elif r < 0.12:
status = status.title() + " " # trailing space
# Nulls: use a mix of true empty strings and sentinel tokens.
def maybe_null(v: str, p: float = 0.04) -> str:
if rng.random() < p:
return rng.choice(["", "", "N/A", "n/a", "NA", "?"])
return v
oid = f"ORD-{10000 + i}"
if rng.random() < 0.03:
oid = oid.replace("-", " ") # ORD 10001
if rng.random() < 0.03:
oid = f" {oid}"
rows.append([
maybe_null(oid, 0.01),
name,
maybe_null(email, 0.05),
maybe_null(city, 0.05),
maybe_null(order_date, 0.03),
quantity,
unit_price_s,
total_s,
maybe_null(payment, 0.04),
status,
])
# --- Inject duplicates -------------------------------------------------
# Exact duplicates (5%) and near-duplicates (3%: same order_id, messy
# casing on a field).
exact_idx = rng.sample(range(len(rows)), 25)
near_idx = rng.sample([j for j in range(len(rows)) if j not in exact_idx],
15)
for j in exact_idx:
rows.append(list(rows[j]))
for j in near_idx:
dup = list(rows[j])
dup[1] = dup[1].strip().lower() # name casing differs
rows.append(dup)
rng.shuffle(rows)
header = ["order_id", "customer_name", "email", "city", "order_date",
"quantity", "unit_price", "total_amount", "payment_method",
"status"]
with out_path.open("w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(header)
w.writerows(rows)
print(f"Wrote {len(rows)} data rows -> {out_path}")
if __name__ == "__main__":
import sys
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(
"messy_orders.csv")
main(target)