Cleaning data in pandas: missing values, duplicates, types and text, with a log that proves every number
TL;DR
Difficulty: Intermediate
Cleaning is a chain of business decisions, so the result is not a tidy table but a bridge: raw rows and revenue, each named rule, clean rows and revenue, closing to the penny.
- In the example shop's July export, eight rules turn 4,830 rows and €296,977 into 3,897 real orders and €258,977 (12.8% less), and paid search ROAS falls from 6.31 to 5.57.
- Count, then cut: print rows and money before and after every rule.
- Find the reason before you fill: blank totals on cancelled orders, unknown channels labelled unattributed, never the average for money.
- Flag, then decide: near duplicates and outliers are questions for a person, not rows to delete.
- Assertions and a totals check run every month, and the code is ready for pandas 3.0.
Every export lies a little: duplicates from overlapping downloads, test orders, refunds as separate rows, money stored as text, timestamps in the wrong time zone. This chapter cleans a shop's July export in pandas one named rule at a time, and logs what each rule does to the revenue, so every number in the final report can be defended.
If you only read one section
Cleaning data sounds like housekeeping. It is not. Every cleaning rule is a business decision that moves a number someone will act on: remove the test orders and paid search earns less, net the refunds and paid social looks weaker, read the timestamps in the wrong time zone and a few orders change month. So the result of cleaning is not a tidy table. The result is a bridge: a short table that walks from the raw export to the clean data one named rule at a time, with the rows and the money removed at each step, and which closes to the penny.
In this chapter the example shop's July export starts at 4,830 rows and €296,977. After eight named rules it ends at 3,897 real orders and €258,977. That is 12.8% less revenue than the raw file shows, and the paid search return on ad spend drops from 6.31 to 5.57. Nobody made a mistake in the shop. The export simply contained duplicates, test orders, staff orders, cancellations, refunds as separate rows, orders from the wrong month and one typo, as almost every real export does.
Three habits carry the whole chapter:
- Count, then cut. Before and after every rule, print the rows and the money. A rule you cannot count is a rule you cannot defend.
- Find the reason before you fill. A missing value is a value with a story. Look for the story (a cancelled order, a declined cookie banner, a coupon nobody used) and the right treatment follows from it.
- Flag, then decide. Near duplicates and outliers are suspects, not culprits. A fence or a match produces a list of questions. A person with the business context answers them, and the answer goes into a log.
If you commission analysis rather than write it, ask for the bridge. If the analyst cannot show you one, the numbers have not been cleaned, they have been changed.
Where this chapter sits
This is chapter 6 of the Python for data analysis series. Pandas Series and DataFrames introduced the tables, and loading business data into pandas got the five exports of the example shop into DataFrames without mangling them on the way in. Here we make them trustworthy. The next chapter joins and reshapes them.
The ideas follow chapter 7 of Wes McKinney's Python for Data Analysis, which covers missing data, duplicates, mapping, replacing, outliers and string methods1. I build on it with business rules the book does not need (test orders, staff orders, refunds, time zones) and with the current pandas API. The third edition came out in 2022. In pandas 2.3, current as I write this in August 2025, a few of its calls have changed, and I point them out where they come up.
Versions used here: Python 3.13, pandas 2.3.1 and NumPy 2.3.2. Every code block runs in order in one notebook, and the outputs shown are the real ones.
The example: Ardmore Home's July export
Ardmore Home is an invented online homeware shop in Sligo: candles, ceramics and textiles, about 1,200 products, roughly 48,000 orders a year from about 21,000 customers, an average order value of about €66 and a gross margin of 52%. Áine founded it. Darragh is the analyst, and his standing question is: "Which channel really pays back, and what should we do with next month's budget?"
To answer it for July he needs revenue by channel he can trust. He exported the shop's orders for 30 June to 1 August, a day of margin either side, because the shop filters its export by UTC and he already suspects that matters. He also has the Google Ads campaign report and the Meta Ads spend for the month.
Example: building the practice export
You do not have Ardmore's data, so the first three blocks build a file that behaves like it. Each trap is planted on purpose, and each one has its own section later. If you only want the cleaning, run these three blocks and skim them.
The first block creates the genuine customer orders in shop time, then adds the orders that the team placed on the live shop: test orders and staff orders.
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=6)
SHOP = "ardmorehome.example"
SHOP_TZ = "Europe/Dublin"
n = 4_400
# The real customer orders, in shop time, 30 June to 1 August (a day of margin each side)
day = rng.choice(pd.date_range("2025-06-30", "2025-08-01"), size=n)
hour_w = np.array([2, 0, 0, 0, 0, 0, 1, 3, 5, 6, 7, 7, 8, 7, 6, 6, 6, 7, 8, 9, 10, 9, 7, 4], float)
hour = rng.choice(24, size=n, p=hour_w / hour_w.sum())
orders = pd.DataFrame({
"local": day + pd.to_timedelta(hour, "h") + pd.to_timedelta(rng.integers(0, 3600, n), "s"),
"channel": rng.choice(["organic", "paid_search", "paid_social", "email", "direct", "referral", "unknown"],
size=n, p=[0.27, 0.24, 0.18, 0.12, 0.13, 0.03, 0.03]),
"amount": np.round(rng.lognormal(4.03, 0.55, n), 2),
"email": [f"cust{c}@mail.example" for c in rng.integers(1, 21_000, n)],
"status": np.where(rng.random(n) < 0.03, "cancelled", "paid"),
"code": np.where(rng.random(n) < 0.18, "SUMMER10", None),
"kind": "sale",
})
orders.loc[[100, 2_000], "email"] = "j.testa@mail.example" # a real customer called Testa
orders.loc[1_500, ["local", "amount", "channel", "status"]] = [pd.Timestamp("2025-07-09 11:05"), 5_200.00, "direct", "paid"]
orders.loc[2_500, ["local", "amount", "channel", "status"]] = [pd.Timestamp("2025-07-17 10:42"), 3_370.00, "referral", "paid"]
# Test orders and staff orders, placed by the team on the live shop
tests = pd.DataFrame({
"local": pd.Timestamp("2025-07-01 09:00") + pd.to_timedelta(rng.integers(0, 43_200, 23), "min"),
"channel": ["direct"] * 12 + ["paid_search"] * 8 + ["unknown"] * 3,
"amount": np.r_[[0.01, 1.00] * 4, np.round(rng.lognormal(4.33, 0.4, 15), 2)],
"email": [f"test@{SHOP}", f"aine+test@{SHOP}", f"darragh+test@{SHOP}"] * 7 + [f"test@{SHOP}"] * 2,
"status": "paid", "code": ["TEST100"] * 9 + [None] * 14, "kind": "sale",
})
staff = pd.DataFrame({
"local": pd.Timestamp("2025-07-01 08:00") + pd.to_timedelta(rng.integers(0, 43_200, 41), "min"),
"channel": ["email"] * 25 + ["direct"] * 16,
"amount": np.round(rng.lognormal(3.93, 0.5, 41), 2),
"email": [f"{name}@{SHOP}" for name in ["aine", "darragh", "ciara", "eoin"] * 11][:41],
"status": "paid", "code": "STAFF30", "kind": "sale",
})
orders = pd.concat([orders, tests, staff], ignore_index=True).sort_values("local", ignore_index=True)
orders["order_id"] = [f"AH-{100_001 + i}" for i in range(len(orders))]
print(len(orders))
# 4464
The second block adds what happens after the sale: 14 double submissions (the same customer and basket again, seconds later, under a new order number) and the refunds, which the shop exports as separate rows with a negative amount. Paid social gets a higher refund rate than the other channels, as impulse purchases often do in a shop like this. Some refunds belong to June orders that are not in the file at all.
# Double submissions: the same customer and basket again, seconds later, under a new order number
customers = orders[(orders["status"] == "paid") & orders["email"].str.startswith("cust")]
in_july = customers[customers["local"].between("2025-07-02", "2025-07-25")]
doubles = in_july.sample(14, random_state=6).assign(
local=lambda d: d["local"] + pd.to_timedelta(rng.integers(20, 90, 14), "s"),
order_id=[f"AH-{200_001 + i}" for i in range(14)],
)
# Refunds arrive as separate rows with a negative amount
rate = {"organic": 0.05, "paid_search": 0.06, "paid_social": 0.12, "email": 0.04,
"direct": 0.04, "referral": 0.05, "unknown": 0.05}
refunds = customers[rng.random(len(customers)) < customers["channel"].map(rate)].copy()
partial = rng.random(len(refunds)) < 0.2
refunds["amount"] = -np.where(partial, np.round(refunds["amount"] * 0.5, 2), refunds["amount"])
refunds["local"] = refunds["local"] + pd.to_timedelta(rng.integers(3, 21, len(refunds)), "D")
caught = doubles.iloc[:11].assign(amount=lambda d: -d["amount"], local=lambda d: d["local"] + pd.Timedelta(days=1))
june = pd.DataFrame({ # refunds of June orders, which are not in this file
"local": pd.Timestamp("2025-07-01 10:00") + pd.to_timedelta(rng.integers(0, 20_160, 25), "min"),
"order_id": [f"AH-0{99_100 + 7 * i}" for i in range(25)],
"channel": rng.choice(["organic", "paid_search", "paid_social", "email"], 25),
"amount": -np.round(rng.lognormal(4.03, 0.5, 25), 2),
"email": [f"cust{c}@mail.example" for c in rng.integers(1, 21_000, 25)],
})
refunds = pd.concat([refunds, caught, june], ignore_index=True)
refunds = refunds.assign(refund_of=refunds["order_id"], kind="refund", status="refunded", code=None)
refunds = refunds[refunds["local"] < "2025-08-02"].copy() # later refunds are not exported yet
refunds["order_id"] = [f"R-{5_001 + i}" for i in range(len(refunds))]
events = pd.concat([orders, doubles, refunds], ignore_index=True).sort_values("local", ignore_index=True)
print(len(doubles), len(refunds), len(events))
# 14 218 4696
The third block writes everything the way the shop exports it: timestamps in UTC as text, channel labels in whatever spelling each tool used, money as text with and without the euro sign, blank totals on some cancelled orders, and one day (15 July) twice, because Darragh exported the month in two halves that overlapped.
# Write it the way the shop exports it: UTC as text, untidy labels, money as text
labels = {
"organic": ["google / organic", "Organic Search", "organic "],
"paid_search": ["google / cpc", "Paid Search", "paid_search", "CPC"],
"paid_social": ["facebook / paid", "Paid Social", "ig / paid", "meta_ads"],
"email": ["newsletter / email", "Email", "EMAIL "],
"direct": ["(direct) / (none)", "Direct"],
"referral": ["partnerblog.example / referral", "Referral"],
"unknown": [None, "", "(not set)"],
}
def as_text(x):
s = f"€{abs(x):,.2f}" if rng.random() < 0.5 else f"{abs(x):,.2f}"
return "-" + s if x < 0 else s
export = pd.DataFrame({
"order_id": events["order_id"],
"created_at": (events["local"].dt.tz_localize(SHOP_TZ).dt.tz_convert("UTC")
.dt.strftime("%Y-%m-%dT%H:%M:%SZ")),
"email": events["email"],
"channel": [labels[c][rng.integers(len(labels[c]))] for c in events["channel"]],
"status": events["status"],
"row_type": events["kind"],
"refund_of": events["refund_of"],
"discount_code": events["code"],
"total": [as_text(x) for x in events["amount"]],
})
cancelled = export.index[export["status"] == "cancelled"]
export.loc[cancelled[:6], "total"] = "" # the shop blanks some cancelled totals
overlap = export[export["created_at"].str.startswith("2025-07-15")]
export = pd.concat([export, overlap], ignore_index=True) # two exports overlapped on 15 July
print(export.shape)
# (4830, 9)
From here on, export is the file Darragh downloaded. Everything below works on it, and only on it.
Look before you touch anything
The first job is not to fix anything. It is to see what you have. Three looks cover most exports: the column types, the missing values, and the distinct values of every text column that you will group by.
Example: three looks at the raw export
export.info()
# RangeIndex: 4830 entries, 0 to 4829
# # Column Non-Null Count Dtype
# 0 order_id 4830 non-null object
# 1 created_at 4830 non-null object
# 2 email 4830 non-null object
# 3 channel 4787 non-null object
# 4 status 4830 non-null object
# 5 row_type 4830 non-null object
# 6 refund_of 225 non-null object
# 7 discount_code 816 non-null object
# 8 total 4830 non-null object
Every column is object, which in pandas 2.3 means "Python objects, usually text". The money is text. The dates are text. Nothing can be summed or compared yet.
print(export.isna().sum())
# channel 43
# refund_of 4605
# discount_code 4014
# (all other columns 0)
print((export == "").sum()[lambda s: s > 0])
# channel 57
# total 6
The second line is the one most tutorials skip. isna() only finds real missing values (None or NaN). An empty string is not missing to pandas, it is a piece of text with no letters in it. This export has 57 channels and 6 totals that are empty strings, invisible to isna(). A third kind hides in the channel counts:
print(export["channel"].value_counts(dropna=False))
# google / organic 475
# Organic Search 453
# organic 431
# (direct) / (none) 318
# Direct 306
# Paid Search 294
# paid_search 292
# CPC 291
# google / cpc 266
# Paid Social 233
# ig / paid 224
# facebook / paid 216
# meta_ads 202
# newsletter / email 191
# EMAIL 186
# Email 183
# Referral 72
# 57
# partnerblog.example / referral 54
# (not set) 43
# None 43
Seventeen spellings of six channels, plus three kinds of "we do not know": a real missing value (None), an empty string, and the placeholder (not set), which analytics tools write when they have no value. A spreadsheet pivot on this column would give you 21 channels. That is the first thing to fix, and it is a text problem, not a missing data problem. If you want a picture of this kind of mess before you fix it, exploring data with charts before you present anything shows the same habit with charts.
Never edit the raw data, and log every step
Two rules make cleaning reviewable. First, the raw export stays exactly as downloaded. Every step produces a new DataFrame, so you can always go back and compare. Second, every step writes one line into a cleaning log: what the rule was, how many rows and how much money remain, and why.
The log is what turns a sequence of filters into the bridge from the first section. It also answers the question every manager eventually asks: "why does your number differ from the shop's dashboard?"
Example: a log function in five lines
The log needs money as a number, so I first convert the types (the next three sections explain each conversion), then start logging. The function is deliberately small:
log = []
def record(step, data, note=""):
log.append({"step": step, "rows": len(data), "revenue": round(data["amount"].sum(), 2), "note": note})
print(f"{step:<34}{len(data):>6} rows €{data['amount'].sum():>12,.2f}")
Call it after every rule. At the end, pd.DataFrame(log) is your bridge. In a real project I would also write the log to a file next to the clean data, with the date and the name of the export it came from.
Types first: money that arrives as text
Before you can count revenue, the total column has to become a number. It contains values like €40.38, 155.22 and €1,240.00. Python cannot add those up.
The tool is pd.to_numeric. Its errors parameter decides what happens to a value that will not convert: "raise" (the default) stops with an error, and "coerce" turns it into NaN2. Coerce is the useful one for cleaning, but only if you then count the NaN it created. Coercing and moving on is how values vanish silently.
One API note: the third option, errors="ignore", which returned the input unchanged, was deprecated in pandas 2.23. If you see it in older code, replace it.
Example: converting the totals and counting what failed
First strip the euro sign and the thousands commas with a regular expression (the character class [€,] means "a euro sign or a comma"), then convert:
amount = pd.to_numeric(export["total"].str.replace(r"[€,]", "", regex=True), errors="coerce")
print(amount.isna().sum())
# 6
print(export.loc[amount.isna(), "status"].value_counts())
# cancelled 6
Six values failed to convert. The second line asks the question that matters: which rows are they? All six are cancelled orders, the ones whose totals the shop blanked. That is a harmless reason, and it tells me what to do: nothing yet, because the cancellation rule will remove those rows anyway. I will check later, with an assertion, that no missing amount survives on an order that was paid.
If one of the six had been a paid order, the right move would have been to look it up in the shop or the payment provider, not to fill it with an average. Which brings us to missing values in general.
Missing values: find the reason before you fill
pandas gives you three tools for missing values: isna() to find them, dropna() to drop rows or columns that have them, and fillna() to replace them with something4. The tools are easy. The judgement is the hard part, and it depends on why the value is missing.
Statisticians sort missing data into three kinds5. In plain words:
- Missing completely at random: the gap has nothing to do with anything. A server hiccup lost a few rows at random. Dropping them loses precision but does not bias the result.
- Missing at random: the gap depends on something you can see in the data. Totals are blank only on cancelled orders. Once you account for the status, the gap is explained.
- Missing not at random: the gap depends on the missing value itself, or on something you cannot see. Customers who decline the cookie banner have no channel, and they may well behave differently from those who accept. No fill can recover that. You can only report it honestly.
From that, a working table of when each tool is honest:
| Situation | Honest treatment | Dishonest treatment |
|---|---|---|
| Missing means "none" (no discount code used) | fillna("none") or fillna(0) | dropping the rows |
| Missing because of a known status (blank total on a cancelled order) | the status rule removes the rows, then assert nothing is left | filling with the average order value |
| Missing category you cannot know (no channel) | an explicit label such as unattributed, reported as its own line | spreading it over the other channels, or filling with the most common channel |
| Missing money on a paid order | look it up at the source, record the correction | filling with the mean or median |
| An ordered state that carries forward (last known price) | ffill() within the group, documented | ffill() across groups |
| The row cannot answer this question at all | filter it out with a named rule | dropna() on every column |
The last line is the one I care most about. dropna() removes rows for having a hole. A business filter removes rows for a reason. In this export, dropna(subset=["amount"]) would remove the 6 cancelled orders with blank totals and keep the other 124 cancelled rows, because they still carry a total. The status rule removes all of them for the right reason. Filter for a reason, never for a hole.
Mean filling deserves its own warning. Replacing missing values with the average distorts the distribution: it piles values up at the mean and makes the data look less spread out than it is6. For revenue it also invents money. If you ever see fillna(df["amount"].mean()) in a revenue pipeline, ask what happened to the orders it filled.
One note on the current API, a difference from McKinney's book: the book fills forward with fillna(method="ffill"), which pandas deprecated in version 2.1 in favour of calling ffill() directly7. The older alias isnull() still works, but isna() is the name the documentation uses4.
Example: three honest fills on the Ardmore export
The export has three columns with gaps, and each gets the treatment its reason calls for.
discount_code is missing on 4,014 rows because those orders used no code. Missing means "none", so filling is honest:
discount_code = export["discount_code"].fillna("none")
channel is missing (in three disguises) on 143 rows, because the visitor declined tracking or arrived in a way nothing could attribute. That is the third kind of missing: I cannot know the true channel. So it becomes its own label, unattributed, and stays visible in every report. The code is in the text section below, because the label needs the other spellings fixed first. Why consent produces these gaps is covered in event tracking and consent mode.
refund_of is missing on every sale row, because only refund rows point at an order. That gap is structural. Nothing to fill.
Dates and time zones: whose July is it?
The shop writes created_at in UTC, the reference time with no daylight saving. Ardmore Home runs on Irish time, which in July is one hour ahead of UTC. An order placed at 00:30 on 1 August in Sligo is stamped 2025-07-31T23:30:00Z. If you filter July by the UTC date, that order counts in July. Áine would count it in August, and so does the bank.
Two pandas steps fix it. pd.to_datetime turns text into timestamps. Giving it the exact format makes it faster and makes it fail loudly on anything that does not match, and utc=True marks the result as UTC8. Then .dt.tz_convert() moves the timestamps into the shop's time zone9. Use the zone name (Europe/Dublin), never a fixed offset such as +01:00. The name comes from the IANA time zone database, which knows when the clocks change. A fixed offset is wrong for half the year10.
Example: counting July twice
created_utc = pd.to_datetime(export["created_at"], format="%Y-%m-%dT%H:%M:%SZ", utc=True)
created = created_utc.dt.tz_convert(SHOP_TZ)
naive_july = created_utc.dt.month.eq(7) & export["row_type"].eq("sale")
true_july = created.dt.month.eq(7) & export["row_type"].eq("sale")
print(naive_july.sum(), true_july.sum())
# 4368 4367
print(export.loc[naive_july != true_july, "created_at"].str[:10].value_counts())
# 2025-07-31 3
# 2025-06-30 2
Five sale rows change month. Three were placed after midnight on 1 August in Sligo but carry a UTC date of 31 July. Two were placed just after midnight on 1 July and carry a UTC date of 30 June. Ardmore sells little after midnight, so the effect is small here. A shop with a busy late evening moves far more, and a shop in Germany, two hours ahead of UTC in summer, moves everything ordered in the first two hours of each month. The same trap sits in the GA4 export to BigQuery, whose event_date follows the property's time zone while event_timestamp is in UTC11. Compare two sources on the same clock, or they will never agree.
Text: one channel, seventeen spellings
Most text cleaning in pandas runs through the .str accessor, which applies Python's string methods to a whole column at once and skips missing values instead of crashing on them12. The everyday ones: .str.strip() removes spaces at both ends, .str.lower() makes case consistent, .str.replace() and .str.contains() work with plain text or regular expressions, and .str.extract() pulls a matching part into a new column. Regular expressions follow Python's re module13.
Then two tools turn many spellings into one value. .map() takes a dictionary and looks each value up, and anything not in the dictionary becomes NaN14. .replace() swaps only the values you list and leaves the rest alone. For cleaning I prefer map, precisely because it does not leave the rest alone: an unknown spelling shows up as NaN instead of slipping through untouched.
Finally, a categorical type with a fixed list of allowed values is a free check. Any value outside the list becomes NaN when you convert15, so if the count of missing values does not change, every label is one you expected. It also keeps the channels in the order you want in every table and chart.
Example: from 21 labels to 7 channels
Strip and lower first, which already merges Email, EMAIL and email:
channel_text = export["channel"].str.strip().str.lower()
Then map every known spelling to its channel, and look at what is left over before deciding anything:
CHANNELS = ["organic", "paid_search", "paid_social", "email", "direct", "referral", "unattributed"]
channel_map = {
"google / organic": "organic", "organic search": "organic", "organic": "organic",
"google / cpc": "paid_search", "paid search": "paid_search", "paid_search": "paid_search", "cpc": "paid_search",
"facebook / paid": "paid_social", "paid social": "paid_social", "ig / paid": "paid_social", "meta_ads": "paid_social",
"newsletter / email": "email", "email": "email",
"(direct) / (none)": "direct", "direct": "direct",
"partnerblog.example / referral": "referral", "referral": "referral",
}
channel = channel_text.map(channel_map)
print(channel_text[channel.isna()].value_counts(dropna=False))
# 57
# (not set) 43
# None 43
The leftovers are exactly the three disguises of "unknown" and nothing else. Now, and only now, the fill is safe. Then the categorical type checks that nothing outside the seven channels got through:
channel = channel.fillna("unattributed").astype(pd.CategoricalDtype(CHANNELS))
assert channel.notna().all(), "a label that is not one of the seven channels"
print(channel.value_counts())
# organic 1359
# paid_search 1143
# paid_social 875
# direct 624
# email 560
# unattributed 143
# referral 126
Next month someone will launch a TikTok campaign tagged tiktok / paid. The map returns NaN for it, the leftover check shows it, and the assertion stops the run before it disappears into unattributed. That is the point of the order: map, inspect leftovers, fill, assert. The cure for seventeen spellings at the source is a naming convention, which mastering UTM tracking sets out.
Building the working table and starting the log
With money, dates and channels converted, I assemble one working DataFrame from the raw export plus the converted columns. Emails get stripped and lowered too, because the business rules below match on them. The raw export stays untouched.
A short note on personal data: the email column identifies people. Use it for matching, then drop or pseudonymise it before the clean data goes anywhere else, as the loading chapter describes.
Example: the first line of the bridge
df = export.assign(amount=amount, created=created, channel=channel,
email=export["email"].str.strip().str.lower(),
discount_code=discount_code)
record("raw export", df)
# raw export 4830 rows € 296,977.06
€296,977.06 is what you get if you sum the total column as exported, refunds and all. It is the number a spreadsheet gives you, which is why it is the starting point of the bridge. (If you sum only the sale rows, as many shop reports do, you get €310,082.07 from 4,605 rows, which is further still from the truth.)
Duplicates: exact ones first
An exact duplicate is a row identical to another in every column. df.duplicated() marks every repeat after the first occurrence. With keep=False it marks all copies, which is handy for inspecting them, and subset=[...] compares only some columns. drop_duplicates() removes them in one step16.
Before you remove duplicates, find out where they came from. In business exports the usual causes are an overlapping date range, an export run twice, or a join that multiplied rows. The cause tells you whether you have found all of them.
Example: the overlapping day
dupes = df.duplicated()
print(dupes.sum(), df.loc[dupes, "created_at"].str[:10].unique())
# 134 ['2025-07-15']
df = df[~dupes]
assert df["order_id"].is_unique
record("exact duplicates removed", df, "15 July exported twice")
# exact duplicates removed 4696 rows € 288,764.20
All 134 duplicates come from one date, 15 July, which confirms the cause: the two halves of the export overlapped on that day. The assertion afterwards checks that every order number now appears once. Had it failed, there would be duplicates that are not identical, which is a different problem (two versions of the same order) and needs a decision about which version is right.
Business rules: test orders, staff orders and cancellations
Some rows are perfectly valid data and still do not belong in a marketing analysis. Test orders are real rows in the shop's database but not sales. Staff orders are real sales but not the result of marketing. Cancelled orders were never paid. None of these can be found by a generic cleaning function. They are business rules, and they need someone who knows the business to define them.
The trap in writing them is precision. A rule that is too loose removes real customers. A rule that is too tight leaves tests in. So every rule gets the same treatment: write it, look at what it matches, then apply it.
Example: the test order rule, and the customer called Testa
The obvious rule is "the email contains test". Look at what it matches before using it:
naive = df["email"].str.contains("test")
print(df.loc[naive, "email"].value_counts())
# test@ardmorehome.example 9
# darragh+test@ardmorehome.example 7
# aine+test@ardmorehome.example 7
# j.testa@mail.example 2
Two of those orders belong to a real customer whose surname is Testa. The loose rule would have deleted her. The precise rule uses a regular expression that only matches test as the whole name before the @ or after a plus sign, and adds the test discount code:
is_test = (df["email"].str.contains(r"(?:^|\+)test@", regex=True)
| df["discount_code"].eq("TEST100"))
print(is_test.sum(), df.loc[is_test, "channel"].value_counts().to_dict())
# 23 {'direct': 12, 'paid_search': 8, 'unattributed': 3, ...}
df = df[~is_test]
record("test orders removed", df, "test@ addresses or code TEST100")
# test orders removed 4673 rows € 287,357.73
Look at the channels: 8 of the 23 tests came in through paid search, because the team clicked their own ads to check the landing pages. Left in, they would have credited Google Ads with sales it never made.
Example: staff orders go into their own table
Staff orders are real revenue, so I do not delete them. I move them out of the marketing analysis into a table of their own, where Áine can still see them:
is_staff = df["email"].str.endswith("@" + SHOP) | df["discount_code"].eq("STAFF30")
staff_orders = df[is_staff]
df = df[~is_staff]
print(len(staff_orders), round(staff_orders["amount"].sum(), 2))
# 41 2202.85
record("staff orders set aside", df, "own domain or code STAFF30")
# staff orders set aside 4632 rows € 285,154.88
25 of the 41 came in through the newsletter, because staff are on the mailing list and click it like everyone else.
Example: cancellations, and the assertion promised earlier
df = df[df["status"].ne("cancelled")]
assert df["amount"].notna().all(), "money missing on an order that was not cancelled"
record("cancelled orders removed", df, "never paid")
# cancelled orders removed 4502 rows € 277,537.92
130 cancelled rows go, including the 6 with blank totals. The assertion closes the loop from the types section: no row that remains is missing its money.
Refunds belong to the order they reverse
This is the rule with the most room for an honest disagreement, so it deserves the most care. The shop exports a refund as its own row, dated the day of the refund, with a negative amount and the original order number in refund_of. There are two defensible ways to count it:
- Cash view: a refund counts in the month it was paid out. This is what the bank account and the accounts show.
- Order view: a refund counts against the order it reverses, in that order's month and channel. This is what you need to judge a channel, because the channel produced the order and the refund together.
For Darragh's question (which channel pays back) the order view is the right one. Two consequences follow, and both are traps.
First, the month filter must apply to sales only. A refund dated 3 August for an order from 28 July belongs to July. Filter all rows by month and you lose it. And refunds paid after the export date are not in the file yet, so July's net revenue will fall a little further once August's refunds arrive. Expect to restate the month, and say so when you report it.
Second, refunds of orders outside the period are set aside, not netted. The file contains refunds of June orders. They reduce June's revenue, not July's.
Example: the month rule, applied to sales only
outside = df["row_type"].eq("sale") & df["created"].dt.month.ne(7)
print(outside.sum())
# 235
df = df[~outside]
record("sales outside July removed", df, "shop time, not UTC")
# sales outside July removed 4267 rows € 262,113.07
The 235 rows are the margin days, 30 June and 1 August in shop time, which Darragh exported on purpose.
Example: netting the refunds onto their orders
is_refund = df["row_type"].eq("refund")
refund_rows = df[is_refund]
sales = df[~is_refund].copy()
per_order = refund_rows.groupby("refund_of")["amount"].sum()
matched = refund_rows["refund_of"].isin(sales["order_id"])
print(len(refund_rows), matched.sum(), (~matched).sum(), round(refund_rows.loc[~matched, "amount"].sum(), 2))
# 218 187 31 -2012.27
sales["refunded"] = sales["order_id"].map(per_order).fillna(0)
sales["net"] = sales["amount"] + sales["refunded"]
df = sales.assign(amount=sales["net"])
record("refund rows netted onto orders", df, "refunds of other months set aside")
# refund rows netted onto orders 4049 rows € 264,125.34
Of 218 refund rows, 187 match a July order and are netted onto it. 31 belong to orders that are not July sales (25 June orders and 6 from the margin day) and are set aside, worth €2,012.27. That is why revenue goes up at this step: those refunds were dragging July down in the raw sum, and they belong to another month. Notice the fillna(0) on refunded: an order with no refund row really has nothing refunded so far, so zero is the honest value.
Example: fully refunded orders are not sales
An order refunded in full has a net value of zero. Should it count as an order? For conversion rate and average order value, I say no: the customer did not end up buying. This is a decision, so it goes in the log with its reason, and Áine can overrule it.
fully = df["amount"].le(0)
print(fully.sum())
# 152
df = df[~fully]
record("fully refunded orders removed", df, "count as no sale")
# fully refunded orders removed 3897 rows € 264,125.34
152 orders go and revenue does not move, because their net was zero. 11 of them are the second half of a double submission that the shop had already spotted and refunded, which brings us to the near duplicates.
Near duplicates: suspects, not culprits
A near duplicate is two rows that are not identical but probably describe one event: the same customer, the same amount, a minute apart, under two order numbers. It happens when a customer double clicks the pay button, or the payment page retries after a timeout.
pandas has no single function for this, and it should not, because "near" is a business definition. The pattern is: sort by time, group by the fields that should match, and measure the gap to the previous row in the group with .diff().
The rule for what to do with the matches is the most important sentence in this section: flag them, do not drop them. Two identical baskets a minute apart may be a double submission, or a customer buying the same gift twice. And if the shop already refunded the second order, dropping it as well removes it twice: once as a refund, once as a duplicate.
Example: finding the double submissions that slipped through
df = df.sort_values("created")
gap = df.groupby(["email", "amount"])["created"].diff()
suspects = df[gap.lt(pd.Timedelta(minutes=2))]
print(suspects[["order_id", "created", "email", "amount"]])
# order_id created email amount
# 991 AH-200012 2025-07-07 10:36:12+01:00 cust15005@mail.example 61.39
# 1926 AH-200014 2025-07-13 22:07:27+01:00 cust4918@mail.example 37.55
Two pairs are left. The other double submissions were already refunded and left with the fully refunded orders. These two were not refunded. Darragh does not delete them. He sends the two order numbers to Áine, who checks the payment provider: if the customer was charged twice, the shop owes a refund, which is a better outcome than a cleaner spreadsheet. Until she answers, the rows stay in and the log says so.
Outliers: a list of questions, not a list of deletions
An outlier is a value far from the rest. The classic rule is Tukey's fences, which the NIST engineering statistics handbook describes17. Compute the first and third quartiles, the interquartile range between them, and call anything beyond a multiple of that range from the quartiles unusual.
Here is the value below which a quarter of the orders fall, the value below which three quarters fall, the interquartile range between them, and the multiplier: 1.5 for the inner fences, 3 for the outer fences in the NIST description. Quartiles and the interquartile range are explained in Foundations: spread.
Two things go wrong with fences on business data. Order values are skewed: many small orders, a long tail of large ones. On the raw values the upper fence lands just above a normal basket and flags hundreds of genuine good orders. Taking the logarithm first makes the distribution roughly symmetric, and the fences then flag only the truly odd. The second thing is worse: treating the flagged rows as errors. A fence cannot tell a typo from your best customer. Each flagged row is a question for someone who can look it up. How to show the shape of a distribution before you decide anything is the subject of showing distributions.
Example: the fence on raw values flags 166 good orders
plain = df["amount"]
pq1, pq3 = plain.quantile([0.25, 0.75])
pfence = pq3 + 1.5 * (pq3 - pq1)
print(round(pfence, 2), (plain > pfence).sum(), round(plain[plain > pfence].sum(), 2))
# 145.91 166 39938.58
On the raw values the upper fence is €145.91. That flags 166 orders worth €39,938.58, about 15% of July's revenue, and almost all of them are ordinary large baskets: a set of ceramics, a duvet cover with cushions. Delete them as "outliers" and the shop's best customers vanish from the analysis.
Example: the fence on log values flags two
log_amount = np.log(df["amount"])
q1, q3 = log_amount.quantile([0.25, 0.75])
iqr = q3 - q1
flag = (log_amount < q1 - 3 * iqr) | (log_amount > q3 + 3 * iqr)
print(round(np.exp(q1 - 3 * iqr), 2), round(np.exp(q3 + 3 * iqr), 2), flag.sum())
# 4.23 754.09 2
print(df.loc[flag, ["order_id", "created", "channel", "amount"]].sort_values("amount"))
# order_id created channel amount
# 2399 AH-102313 2025-07-17 10:42:00+01:00 referral 3370.0
# 1280 AH-101251 2025-07-09 11:05:00+01:00 direct 5200.0
On the log scale, with the outer fences, the band runs from €4.23 to €754.09 and two orders fall outside. Darragh looks both up. AH-102313 is genuine: a hotel ordered 80 candles for its rooms, came through a partner blog, and paid €3,370. It stays, and it is worth mentioning when referral revenue is discussed, because one order is a third of that channel's month. AH-101251 is a phone order that a member of staff typed into the admin as 5200 instead of 52.00. The payment provider shows €52.00.
Example: correcting a value with a record
A correction is a change to the data, so it is recorded like one: a small table of corrections, applied by code, kept with the log.
typo = df["amount"].eq(5_200.00)
corrections = pd.DataFrame([{
"order_id": df.loc[typo, "order_id"].iloc[0], "column": "amount", "old": 5_200.00, "new": 52.00,
"reason": "phone order typed without decimal point, payment provider shows €52.00",
}])
for c in corrections.itertuples():
df.loc[df["order_id"].eq(c.order_id), c.column] = c.new
record("one typo corrected", df, "see corrections table")
# one typo corrected 3897 rows € 258,977.34
One typo was worth €5,148 of revenue, all of it credited to direct traffic. Note the form of the assignment: df.loc[rows, column] = value, on the DataFrame itself. The next section explains why that matters.
Checks that run every time
Cleaning code runs again every month on a new export, and next month's export will have a problem this month's did not. Assertions are how the code notices. An assert stops the run with a message when its condition is false, so a broken assumption cannot reach a report.
Write the assertions as plain statements about what clean data means for this shop: every order number once, every amount positive, every order in the month, no staff email left, every row with a channel. Then add the one check that ties everything together: the bridge closes.
There is one more habit worth building now, because pandas is about to enforce it. The pandas 2.3 release notes say that pandas 3.0 will switch on copy on write permanently18. Every selection then behaves as a copy, so changing a column through a chain like df["col"].fillna(..., inplace=True) will silently do nothing to df. pandas 2.3 already warns about it:
w = df.copy()
w["discount_code"].replace("none", "no code", inplace=True)
# FutureWarning: A value is trying to be set on a copy of a DataFrame or Series
# through chained assignment using an inplace method.
Write df["col"] = df["col"].fillna(...), or df.loc[...] = ..., or build new columns with assign(), as every block in this chapter does, and your cleaning code will behave the same in pandas 3.0. The same release notes announce a dedicated string type as the default in 3.0, so code that checks dtype == object to find text columns will need a change then18.
Example: the assertion suite and the closing bridge
assert df["order_id"].is_unique
assert df["amount"].gt(0).all()
assert df["created"].dt.month.eq(7).all()
assert not df["email"].str.endswith("@" + SHOP).any()
assert df["channel"].notna().all()
clean = df
bridge = pd.DataFrame(log)
assert round(bridge["revenue"].iloc[-1], 2) == round(clean["amount"].sum(), 2)
print(bridge.to_string(index=False))
Every assertion passes, and the printed log is the bridge, which the next section reads line by line.
What the cleaning did to the numbers
Here is the full bridge for July, rows and revenue after each rule:
| Step | Rows | Revenue | Change in revenue |
|---|---|---|---|
| Raw export | 4,830 | €296,977.06 | |
| Exact duplicates removed (15 July exported twice) | 4,696 | €288,764.20 | €8,212.86 less |
| Test orders removed | 4,673 | €287,357.73 | €1,406.47 less |
| Staff orders set aside | 4,632 | €285,154.88 | €2,202.85 less |
| Cancelled orders removed | 4,502 | €277,537.92 | €7,616.96 less |
| Sales outside July removed (shop time) | 4,267 | €262,113.07 | €15,424.85 less |
| Refund rows netted onto their orders | 4,049 | €264,125.34 | €2,012.27 more |
| Fully refunded orders removed | 3,897 | €264,125.34 | none |
| One typo corrected | 3,897 | €258,977.34 | €5,148.00 less |
| Clean July | 3,897 | €258,977.34 | €37,999.72 less (12.8%) |
The rows tell the same story as a waterfall. Each bar is one rule, and the first and last bars are the totals.
The effect is not spread evenly across channels, and that is what matters for the budget question. To see it, compare revenue per channel in the raw export (with the channel labels already mapped, so the two sides line up) and in the clean data. This is a first taste of groupby, which chapter 8 covers properly. observed=False keeps every channel in the table even if it had no orders.
raw_rows = export.assign(amount=amount.fillna(0), channel=channel)
by_channel = pd.DataFrame({
"raw": raw_rows.groupby("channel", observed=False)["amount"].sum(),
"clean": clean.groupby("channel", observed=False)["amount"].sum(),
}).round(0)
by_channel["change_%"] = ((by_channel["clean"] / by_channel["raw"] - 1) * 100).round(1)
print(by_channel)
# raw clean change_%
# organic 81976.0 73188.0 -10.7
# paid_search 67735.0 59838.0 -11.7
# paid_social 48188.0 43957.0 -8.8
# email 33307.0 28166.0 -15.4
# direct 45238.0 35154.0 -22.3
# referral 10722.0 9898.0 -7.7
# unattributed 9811.0 8776.0 -10.5
Direct loses the most, because it collected the test orders, part of the staff orders and the typo. Paid search loses more than paid social, because of the test orders placed through its ads.
| Channel | Raw revenue | Clean revenue | Change | Raw orders | Clean orders |
|---|---|---|---|---|---|
| Organic | €81,976 | €73,188 | 10.7% less | 1,359 | 1,115 |
| Paid search | €67,735 | €59,838 | 11.7% less | 1,143 | 940 |
| Paid social | €48,188 | €43,957 | 8.8% less | 875 | 679 |
| €33,307 | €28,166 | 15.4% less | 560 | 431 | |
| Direct | €45,238 | €35,154 | 22.3% less | 624 | 511 |
| Referral | €10,722 | €9,898 | 7.7% less | 126 | 105 |
| Unattributed | €9,811 | €8,776 | 10.5% less | 143 | 116 |
Paid social keeps more of its revenue than paid search, yet it loses more of its orders (22%, against 18% for paid search), because so many of its orders are refunded in full. Revenue and order count tell different stories about the same channel, and only the clean data shows both.
Example: the conversion rate and the average order value
GA4 counted 152,400 sessions on the shop in July. The conversion rate is orders per session, and the average order value is revenue per order (Foundations: ratios and rates):
where is the conversion rate, the number of orders, the number of sessions, the average order value and the revenue. With the raw export, counting every sale row as an order, and then with the clean data:
So is 3.02% and is 2.56%. The raw rate overstates conversion by almost half a percentage point, which in a test of a new checkout could easily be the whole effect you were hoping to see. The clean average order value is €258,977.34 divided by 3,897, which is €66.46.
Campaign data has its own traps
The orders are only half of the return on ad spend. The other half is the spend, and ad platform exports come with their own mess: a title block above the header, numbers with thousands separators, and a totals row at the bottom that looks exactly like a campaign. pd.read_csv handles the first two with skiprows and thousands19. The totals row has to be removed by a rule, and it is the most expensive single line in this chapter.
Example: the Google Ads report with a totals row
import io
ads_csv = """Campaign performance report
1 July 2025 to 31 July 2025
Campaign,Clicks,Cost
Search Brand,4210,"1,343.21"
Search Candles,6930,"3,883.47"
Search Ceramics,3880,"2,510.39"
Shopping All Products,5120,"3,005.22"
Total: Account,20140,"10,742.29"
"""
ads = pd.read_csv(io.StringIO(ads_csv), skiprows=2, thousands=",")
print(ads["Cost"].sum())
# 21484.58
ads = ads[~ads["Campaign"].str.startswith("Total")]
assert round(ads["Cost"].sum(), 2) == 10_742.29
Summed with the totals row in, the spend is €21,484.58, exactly double. The assertion compares the sum of the campaigns with the total the platform printed, which is the simplest reconciliation there is: the export checks itself. Meta's spend comes as a clean table in this example, in euro, because the ad account is set to euro. If yours runs in another currency, convert before you compare.
meta = pd.DataFrame({"campaign": ["Prospecting candles", "Retargeting 30 days", "Autumn ceramics teaser"],
"spend": [4_688.62, 2_628.73, 1_115.40]})
spend = pd.Series({"paid_search": ads["Cost"].sum(), "paid_social": meta["spend"].sum()})
print(spend.round(2).to_dict())
# {'paid_search': 10742.29, 'paid_social': 8432.75}
Example: return on ad spend, raw against clean
Return on ad spend (ROAS) is revenue divided by spend (Foundations: ratios and rates):
where is the revenue attributed to channel and the spend on that channel. For paid search, raw and clean:
Every euro spent on paid search brought back €5.57 in clean revenue, not €6.31, so is the figure to plan with. The same calculation for both channels in code:
roas = pd.DataFrame({"spend": spend,
"revenue_raw": by_channel.loc[spend.index, "raw"],
"revenue_clean": by_channel.loc[spend.index, "clean"]})
roas["roas_raw"] = (roas["revenue_raw"] / roas["spend"]).round(2)
roas["roas_clean"] = (roas["revenue_clean"] / roas["spend"]).round(2)
print(roas)
# spend revenue_raw revenue_clean roas_raw roas_clean
# paid_search 10742.29 67735.0 59838.0 6.31 5.57
# paid_social 8432.75 48188.0 43957.0 5.71 5.21
Now add the totals row mistake on top:
print(round(by_channel.loc["paid_search", "raw"] / (spend["paid_search"] * 2), 2))
# 3.15
With the doubled spend and the raw revenue, paid search shows a ROAS of 3.15. So the same month can be reported as 6.31, 5.57 or 3.15 depending on which mistakes were made. Errors do not cancel out. They pull in different directions, by different amounts, and you cannot tell from the final number which ones are in it.
The cleaning pipeline, step by step
The order of the steps is not arbitrary. Types come first, because nothing can be counted until money is a number. Exact duplicates go before the business rules, so each rule counts real rows. The month filter applies to sales only, before refunds are netted, so refunds of July orders are kept wherever they were dated. Near duplicates and outliers come last, on data that is otherwise clean, because only then do the remaining oddities stand out.
Put this whole sequence into one function that takes the raw export and returns the clean data, the log and the corrections, and you have a cleaning step you can run every month in seconds. How to turn notebook code like this into a tested script is the subject of the last chapter of this series.
For the person who commissions this
You do not need to read the code to judge the cleaning. Ask five questions:
- Can you show me the bridge? Raw rows and revenue, each rule, clean rows and revenue, closing to the penny. If there is no bridge, there is no audit trail.
- Which rules are business decisions, and who signed them off? The refund view, what counts as a staff order, whether fully refunded orders count. These belong to the owner, written in plain words.
- What did you do with missing values? "Filled with the average" is the wrong answer for money. "Labelled unattributed and reported" is the right one for channels.
- What did you delete as an outlier? The right answer is usually "nothing, I checked two orders and corrected one, here is the record".
- Does the clean revenue reconcile with something outside the data? The payment provider's payouts or the accounts, within a known gap for fees and timing.
My view: cleaning rules are the business's rules, and they should be written down where the business can read and argue with them, not buried in a notebook or in someone's spreadsheet habits. My own rule of thumb is that any rule that moves revenue by more than 1% needs a name in the log and a person who agreed to it. In the Ardmore example that is four of the eight rules. A clean dataset with no bridge is just a different number, and a different number with no explanation is worse than the raw one, because it looks trustworthy.
Data storytelling, analytics dashboards and data science are a core part of my work for clients, and a cleaning bridge like this is where every one of those starts. If you want the same for your own exports, my data science work starts there, and the free workshop is the place to look at your data together first.
Conclusion
Clean data is not data with the bad rows removed. It is data where every change is named, counted and agreed. In pandas that takes a handful of tools (to_numeric, to_datetime with tz_convert, the .str accessor, map with a categorical check, duplicated, a groupby with diff, quartile fences on a log scale) and three habits: count, then cut; find the reason before you fill; flag, then decide.
For Ardmore Home in July, that turned €296,977 into €258,977, 4,605 apparent orders into 3,897 real ones, and a paid search ROAS of 6.31 into 5.57. Darragh can now answer Áine's budget question with numbers he can defend line by line. The next chapter joins these clean orders to the GA4 sessions and the ad spend, so that every channel's return comes out of one table.
