DEV Community

CSV bugs that don't raise: 6 silent ways Excel corrupts your revenue numbers

In the first post I listed the five CSV bugs I keep finding in small-business books. This one is the follow-up people actually asked for: what the fix looks like in code, plus three more bugs that only show up after the first ones are fixed.

Everything below is reproducible with pandas and a throwaway CSV. No paid tooling required.

1. Excel eats your SKUs before pandas ever sees them

If someone opens an export in Excel and saves it, 00123 becomes 123, and 1.23E+11 is a number now, not an ID. The damage happens before you load the file, so no amount of dtype=str in pandas saves you.

The only reliable fix is to stop the round-trip:

import pandas as pd

# Read raw, keep everything as text, decide types yourself
df = pd.read_csv("sales.csv", dtype=str, keep_default_na=False, na_values=[""])

# Only these columns are allowed to become numbers
money = ["gross", "fees", "net"]
for c in money:
    df[c] = pd.to_numeric(df[c].str.replace(r"[,$ ]", "", regex=True), errors="coerce")

errors="coerce" is deliberate: it turns silent mis-parses into NaN you can count, instead of raising on line 4,000 and hiding the other 12 bad rows.

bad = df[df[money].isna().any(axis=1)]
print(f"{len(bad)} rows failed to parse - fix these before summing anything")

2. Accounting negatives are strings, not numbers

Exports from QuickBooks, Xero, and a surprising number of banks write refunds as (45.00) and $1,204.50. pd.to_numeric returns NaN for both, and NaN sums to zero - so your refunds quietly disappear and revenue looks better than it is.

def parse_money(s: pd.Series) -> pd.Series:
    s = s.astype(str).str.strip()
    negative = s.str.match(r"^\(.*\)$")
    s = s.str.replace(r"[(),$ ]", "", regex=True)
    out = pd.to_numeric(s, errors="coerce")
    out[negative] *= -1
    return out

Then assert the total row count is preserved:

assert parse_money(df["net"]).notna().sum() == len(df), "unparsed money values"

That single assert has caught more broken month-end reports for me than any dashboard.

3. Float sums that are off by a cent

0.1 + 0.2 == 0.30000000000000004. Sum 4,000 marketplace rows and your P&L is a few cents off - which is exactly the kind of error that makes someone distrust the whole report.

Work in integer minor units when you reconcile, and only round at the edge:

cents = (df["net"].astype(float) * 100).round().astype("int64")
print(cents.sum() / 100) # exact to the cent

If your source is already integer cents, never convert to float in the first place.

4. MERGE with mismatched keys silently doubles revenue

pandas.merge and Excel's VLOOKUP both fail quietly. VLOOKUP's 4th argument defaults to TRUE (approximate match), and merge on dirty keys produces a cartesian product - both inflate totals.

before = len(orders)
df = orders.merge(fees, on="order_id", how="left", validate="one_to_one")
assert len(df) == before, f"row count changed {before} -> {len(df)}"

validate="one_to_one" makes pandas raise instead of silently multiplying rows. It costs one keyword and saves an audit.

5. Invisible whitespace destroys every GROUP BY

Non-breaking spaces (\xa0) from HTML exports and trailing tabs from copy-paste mean "Etsy ", "Etsy" and "Etsy\xa0" are three different categories. Your channel breakdown shows three near-empty rows and nobody notices.

df["channel"] = (df["channel"]
    .astype(str)
    .str.replace("\xa0", " ", regex=False)
    .str.strip()
    .str.lower())
print(df["channel"].value_counts().head(10))

Always print the top-10 values of every categorical column before trusting a pivot.

6. Timezone drift moves sales between months

A marketplace that timestamps in UTC and a bookkeeper in local time will disagree about which month the 30th belongs to. December revenue changes by a few percent depending on where the server sits.

df["ts"] = pd.to_datetime(df["ts"], utc=True, errors="coerce")
df["month"] = df["ts"].dt.tz_convert("America/New_York").dt.to_period("M")

Pick one reporting timezone, write it down, and convert - never filter on a naive string date.

The pattern

Every bug above shares one property: it does not raise. The pipeline finishes, the numbers look plausible, and the error is invisible until a tax filing or a pricing decision is already wrong.

So the fix is not better code - it is assertions that turn silence into noise:

checks = {
    "rows_parsed": lambda d: d["net"].notna().all(),
    "no_row_inflation": lambda d: len(d) == expected_rows,
    "cents_exact": lambda d: d["net_cents"].dtype.kind == "i",
    "no_nbsp": lambda d: not d["channel"].str.contains("\xa0").any(),
}
for name, check in checks.items():
    print(("PASS" if check(df) else "FAIL"), name)

If you want this pre-built rather than copy-pasted: the free mini sample (5 real broken CSVs plus the fixed versions) is here, and the full CLI + audit toolkit that runs these checks as one command is here. Both are plain Python, no subscription.

If you have a CSV that reconciles to the wrong number and you cannot see why - paste the header row and the totals in the comments. That is usually enough to find it.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.