Why pandas quietly shrinks the revenue in a client's messy Excel file
pandas sums missing cells as zero, so count every cell lost when converting types and send the client an error list before the demo.
In brief
- Read client files raw: dtype=str or object for ID columns, per-column na_values, and thousands and decimal for numbers written in the Vietnamese (and European) style.
- pandas treats NA as 0 when summing, so always count how many cells were coerced to NaN before reporting a figure.
- The most valuable output is not the clean file but the list of errors the client can fix themselves.
A thousand orders, forty of them with the words “contact us” in the amount column. Convert that column to numbers, and forty cells become NaN. Call .sum() and the figure that comes back looks perfectly tidy, and is missing exactly forty orders, with no warning at all.
That scenario is hypothetical; the mechanism is not. The pandas documentation states it plainly: when summing, NA values or empty data are treated as zero. For an FDE this is the most dangerous trap of the first week on a client site, because the wrong number ends up on screen at the demo.
This guide walks through a workflow you can run on a laptop tonight: read the raw files, declare missing values, convert types under control, count the damage, then gather the errors into a report for the client. The code is trimmed down for learning; anything simplified is flagged.
What you will build, and what you need
Take a distributor that sends two files: orders.csv and report.xlsx. The CSV has a customer_id column with values like “00123”, an amount column written the Vietnamese way, such as “1.250.000,5” (wrapped in double quotes), and a few cells reading “-” or “not yet”. The Excel file has three decorative header rows at the top and one sheet per branch.
You need Python 3, pandas, whichever Excel reader ships with your environment, and Pandera for the final step. Build the two sample files yourself, about 20 rows each, and plant every kind of junk in them on purpose. Dirtying data by hand is the fastest way to understand what each parameter does.
Step 1: read the CSV without letting pandas guess
The most common mistake is a bare pd.read_csv("orders.csv"). pandas infers types, “00123” becomes the number 123, and the customer ID is ruined for good before you have even looked at it.
import pandas as pd
df = pd.read_csv(
"orders.csv",
dtype={"customer_id": str},
na_values={"amount": ["-", "not yet", "contact us"]},
thousands=".",
decimal=",",
on_bad_lines="warn",
)
The read_csv documentation recommends str or object together with suitable na_values to preserve data as-is rather than have pandas interpret types. na_values accepts a dict to declare missing values per column, added on top of the default list pandas already treats as NaN.
The thousands and decimal parameters handle locale-specific numbers; the documentation’s example uses a comma as the decimal separator for European data, which is also how Vietnamese write numbers. on_bad_lines="warn" warns about and skips lines with too many fields, instead of crashing the whole read or dropping lines silently.
Check after this step: print df.dtypes and df.head(). The customer_id column must still have its leading zeros, and amount must be the float 1250000.5. Read every bad-line warning carefully and note the line numbers, because that is the first item in the report to the client.
Step 2: open each Excel sheet before combining them
A client’s Excel file rarely starts on row 1. The first three rows are usually the company name, the report name and the export date.
sheets = pd.read_excel(
"report.xlsx",
sheet_name=None,
skiprows=3,
dtype=object,
)
for name, table in sheets.items():
print(name, table.shape)
With sheet_name=None, read_excel returns a dict holding a DataFrame for each sheet, so you can see at once how many rows each branch has. dtype=object keeps the data exactly as stored in Excel, with no type inference; the price is that every column becomes object, and you convert types yourself in the next step.
If the sheets carry different amounts of junk at the top, skiprows also accepts a function: it is called on each row index, and rows for which it returns True are skipped. For example, skiprows=lambda i: i in (0, 1, 2). Check: every sheet must have the same number of columns; a sheet that differs is one where the client inserted a column by hand.
Step 3: normalize numeric strings before converting types
After step 2, the amount column from Excel is a mix: cells the client typed as numbers are numbers, cells typed as text are strings like “1.250.000,5”. Feed this column straight into pd.to_numeric and none of the Vietnamese-style strings will parse; with errors="coerce" they all become NaN. You lose perfectly valid cells along with the bad ones.
So a normalization step is needed: strip the thousands dots, turn the decimal comma into a dot, and do this only for cells that are strings. Leave cells that are already numbers alone, because removing the dot from 1250000.5 would turn it into a different number.
table = sheets["Branch_HN"]
def normalize(x):
if isinstance(x, str):
return x.strip().replace(".", "").replace(",", ".")
return x
amount = table["amount"].map(normalize)
already_missing = amount.isna().sum()
table["amount"] = pd.to_numeric(amount, errors="coerce")
lost_in_cast = table["amount"].isna().sum() - already_missing
print("Already blank:", already_missing, "| Unparseable:", lost_in_cast)
By default to_numeric raises an error at the first value it cannot parse. With errors="coerce", that value becomes NaN and the code carries on. Convenient, and precisely where the forty “contact us” orders from the opening vanish from the total.
The normalize function above is simplified: it assumes the whole column is written the Vietnamese way. If the client mixes in American-style “1,250,000.5”, you need extra detection rules, and it is better to ask the client than to guess.
Note how the counting works: isna().sum() on the column itself, separating cells that were blank from the start from cells that broke during conversion. The two numbers mean different things to the client. If only 960 of 1,000 rows still have an amount, every total you report must carry the line “excludes 40 orders with unknown amounts”.
Step 4: deciding what to do with missing cells is the client’s call
pandas gives you two tools: dropna() removes rows or columns with missing data, and fillna() replaces NA with another value. Both take one line of code, and both are business decisions.
Filling the amount column with 0 asserts that those orders were free. Dropping the rows asserts that those orders never existed. The advice: use fillna only on columns where the client has confirmed the rule (an empty notes cell becomes an empty string, say), and keep the amount column as NaN and put it in the error report.
Bear in mind too that pandas uses different sentinel values to represent NA depending on the data type. After fillna or a type conversion, print dtypes again to make sure no column changed type unexpectedly.
Duplicates also belong in this step. A KDnuggets tutorial gives the simple reason: the same record counted several times skews the analysis. When combining several sheets, an order transferred between two branches can easily appear twice; deduplicate on the key column the client confirms, not on the whole row.
Step 5: turn errors into a report the client can read
By now you have a nearly clean file, but the real value lies in the error list. Pandera, an open-source project from Union.ai, lets you declare a schema for a DataFrame and validate against it. A three-column schema for a branch file might look like this.
# Simplified illustration; check API names against your installed Pandera version
import pandera as pa
schema = pa.DataFrameSchema({
"customer_id": pa.Column(str, pa.Check.str_matches(r"^\d{5}$")),
"amount": pa.Column(float, pa.Check.ge(0), nullable=False),
"date": pa.Column("datetime64[ns]"),
})
try:
schema.validate(table, lazy=True)
except pa.errors.SchemaErrors as err:
failures = err.failure_cases
print(failures[["column", "check", "index", "failure_case"]])
failures.to_csv("errors_for_client.csv", index=False)
The key is lazy=True: instead of stopping at the first error, Pandera collects every error into one report. The failure_cases table shows the column, the rule, the row and the offending value. Export it to a file and send it to the client once, rather than ten emails saying “one more error”.
Check: deliberately change one customer ID to “123” and delete one amount cell in the sample file. Both must appear in the same report, not one per run.
The most common mistakes
The first is reading bare and fixing later: once leading zeros are gone, they cannot be recovered from the DataFrame. The next is setting on_bad_lines to skip silently to cut the noise, after which nobody knows how many lines were dropped.
A subtler one is to_numeric with coerce on an Excel column that has not been normalized, as seen in step 3: the code runs smoothly, but half the column disappears. The most dangerous is fillna(0) on the amount column to make a chart look complete. Combined with pandas summing NA as 0, you get a total that is certainly wrong and very convincing.
On a client site, which answer earns trust?
Say it is day one of a project: a folder of Excel files arrives by email, and at the next day’s meeting the client asks, “Does this match our books?”
The weak answer is “it’s all cleaned up”. The good answer is: “We read 1,000 rows; 40 are missing an amount and 3 are badly formatted. Here is the list for you to fix at the source.” That shows the client you understand their data down to the row.
On a CV, don’t write “proficient in pandas”. Describe a specific pipeline: reading multi-sheet files with fixed dtypes, handling numbers in Vietnamese format, and reporting errors with Pandera.
When reading a job description, watch for lines about ingesting client data; if they are there, that is your cue to tell this exact example in the interview.
The cleanest number you can bring to a first meeting is the one that comes with a list of the rows it leaves out.
Was this article useful?
Thanks for the feedback!