Inconsistent Data, Errors, and Outliers (Drafting)#
Even when a dataset has no missing values, it may still contain entries that are incorrect, illogical, inconsistent, or implausible. These problems—collectively referred to as inconsistencies, errors, and outliers—can quietly distort analysis, undermine models, and lead to poor or even risky business decisions. In FinTech, where data flows continuously from customers, merchants, payment networks, and internal systems, these issues are not the exception—they are the norm.
In this chapter, we deepen our understanding of data quality by moving beyond missingness and addressing the broader category of invalid or inconsistent data. We will use two running examples:
the dirty café sales dataset, which lets us illustrate inconsistencies in a simple business setting (mislabeled payment methods, mismatched totals, odd timestamp values), and
a dirty P2P payments dataset, used later for a full case study in a more authentic FinTech scenario.
Although the domains differ, the core principles of diagnosing and correcting inconsistent data are the same.
Inconsistency, Error, and Outlier: Three Related but Distinct Concepts
In practice, data problems blur together. However, distinguishing these three categories helps us reason about causes and choose appropriate treatments:
Inconsistency refers to values that violate expected structure or rules.
Example (café):
"Take Away"vs"Takeaway"vs"takeaway"Example (FinTech):
"usd","Usd ","US D"as currency codes
Error refers to values that are simply wrong.
Example (café):
Total Spent = 9.0forQuantity = 4,Price = 3.0Example (FinTech):
"2029-12-01"timestamp in a system launched in 2023
Outlier refers to values that are statistically extreme but not necessarily wrong.
Example (café): A $400 order may be a catering event or a data-entry mistake—context matters.
Example (FinTech): A $9,999 peer-to-peer payment might be fraud, a business transfer, or a legitimate large repayment.
These categories often overlap. Errors sometimes manifest as outliers. Inconsistencies may mask errors. Outliers may be valid but indicative of special processes (e.g., chargebacks, high-net-worth users). Understanding the distinctions helps guide later decisions.
Why This Matters in FinTech
In consumer apps, a few incorrect values may be harmless. In FinTech systems, inconsistent or incorrect data can have serious consequences:
Fraud detection systems use transaction amounts, timestamps, and user behavior patterns; inconsistent values can produce false positives or allow fraudulent behavior to go undetected.
Credit models rely on clean income, balance, and risk attributes; incorrect values can lead to biased or noncompliant decisions.
Regulatory reporting (AML, KYC) requires data that is both accurate and internally consistent.
Fees and revenue reporting depend on correct, consistent transaction amounts and statuses.
Operational dashboards may trigger alerts or fail silently depending on whether inconsistent data is present.
Because of this, financial institutions invest heavily in data validation, quality monitoring, and lineage tracking—but inconsistencies still arise due to human behavior, system drift, integration challenges, and business complexity.
Everyday Examples of Inconsistency
To make these ideas concrete, consider a few inconsistencies from our café dataset:
Misformatted numbers:
"$4.00","4","4.0 ", and"4,00"all represent the same value but require cleaning.Inconsistent categories:
"Credit Card","creditcard","cc","CREDIT CARD"Without standardization, these appear as different payment methods.Logical contradictions: A record shows
Quantity = 4,Price Per Unit = 3.0, butTotal Spent = "ERROR".Impossible values: A coffee priced at $200 is probably a data entry error, not a premium product.
These are simple examples, but they map directly to problems in financial systems:
"USD","usd","USD "as currency codesinconsistent merchant names across payment networks
negative values for completed transactions
future timestamps
chargebacks mislabeled as “completed”
These inconsistencies may not prevent the data from loading or passing basic type checks—but they can wreak havoc on any downstream analysis.
Our Approach in This Chapter
This chapter follows the same conceptual pattern as the Missing Data chapter:
Describe the types of inconsistencies and errors (schema-level, value-level, business logic, and outliers).
Diagnose them using systematic methods (profiling, type checking, uniqueness analysis, logical rules).
Explain the causes, both technical and human.
Present strategies for handling inconsistencies (standardization, correction, reconstruction, outlier treatment).
Evaluate the impact of our cleaning choices.
Conclude with a full case study using the P2P payments dataset to illustrate the entire workflow.
Throughout these sections, we will regularly use the café dataset to illustrate inconsistent values and cleaning techniques in an approachable environment, before applying the same reasoning to financial transactions.
1import pandas as pd
2
3DATA_PATH = "resources/data/dirty_cafe_sales.csv"
4df = pd.read_csv(DATA_PATH)
5print("Shape:", df.shape)
6df.head(10)
Shape: (10000, 8)
| Transaction ID | Item | Quantity | Price Per Unit | Total Spent | Payment Method | Location | Transaction Date | |
|---|---|---|---|---|---|---|---|---|
| 0 | TXN_1961373 | Coffee | 2 | 2.0 | 4.0 | Credit Card | Takeaway | 2023-09-08 |
| 1 | TXN_4977031 | Cake | 4 | 3.0 | 12.0 | Cash | In-store | 2023-05-16 |
| 2 | TXN_4271903 | Cookie | 4 | 1.0 | ERROR | Credit Card | In-store | 2023-07-19 |
| 3 | TXN_7034554 | Salad | 2 | 5.0 | 10.0 | UNKNOWN | UNKNOWN | 2023-04-27 |
| 4 | TXN_3160411 | Coffee | 2 | 2.0 | 4.0 | Digital Wallet | In-store | 2023-06-11 |
| 5 | TXN_2602893 | Smoothie | 5 | 4.0 | 20.0 | Credit Card | NaN | 2023-03-31 |
| 6 | TXN_4433211 | UNKNOWN | 3 | 3.0 | 9.0 | ERROR | Takeaway | 2023-10-06 |
| 7 | TXN_6699534 | Sandwich | 4 | 4.0 | 16.0 | Cash | UNKNOWN | 2023-10-28 |
| 8 | TXN_4717867 | NaN | 5 | 3.0 | 15.0 | NaN | Takeaway | 2023-07-28 |
| 9 | TXN_2064365 | Sandwich | 5 | 4.0 | 20.0 | NaN | In-store | 2023-12-31 |
Types of Inconsistency and Error#
Missing values are only one way data can fail. Even when every cell is filled, entries may be inconsistent, incorrect, or implausible. These problems fall into four broad categories:
Schema-level inconsistencies
Value-level inconsistencies
Semantic or business-logic errors
Outliers (statistical or domain-based)
Recognizing which kind of problem you’re seeing is essential for deciding how to handle it.
2.1 Schema-Level Inconsistencies#
A schema defines what type of data is expected in each column: integers, floats, dates, categories, etc. Schema-level inconsistencies arise when the actual stored values violate those expectations.
Typical symptoms#
Numeric fields stored as strings (
"4.0"instead of4.0).Mixed types in a single column (
"3",3.0,"three").Date/time fields using multiple formats or invalid values.
Columns containing special error tokens instead of the expected type.
Café dataset: what types did Pandas infer?#
df.dtypes
You will often see:
Quantity,Price Per Unit,Total Spentasobjectinstead of numeric.Transaction Dateasobjectinstead ofdatetime64[ns].
This tells us the inferred schema does not match the intended schema.
Detecting non-numeric entries in numeric columns#
numeric_cols = ["Quantity", "Price Per Unit", "Total Spent"]
coerced = df[numeric_cols].apply(pd.to_numeric, errors="coerce")
invalid_counts = coerced.isna().sum()
invalid_counts
Here, values like "ERROR" in Total Spent become NaN after coercion, revealing schema violations.
Detecting inconsistent date formats#
parsed_dates = pd.to_datetime(df["Transaction Date"], errors="coerce")
parsed_dates.isna().sum()
df.loc[parsed_dates.isna(), "Transaction Date"].head(10)
Rows where parsed_dates is NaN are using formats that don’t match the rest—or are simply invalid.
FinTech analogy#
Schema-level inconsistencies are common when combining data from multiple systems:
A card network sends
"MM/DD/YYYY"dates, while internal systems use"YYYY-MM-DD".Legacy AML logs store timestamps as UNIX integers, while modern systems use ISO-8601 strings.
Transaction amounts come as strings with currency symbols from some APIs and as pure numerics from others.
The column type might be “string” everywhere, but the schema of how that string is supposed to look is inconsistent.
2.2 Value-Level Inconsistencies#
Even if the type is correct (e.g., strings for categories, floats for amounts), individual values can still be inconsistent or messy.
Types of value-level inconsistencies#
Category variants:
"Takeaway","take away","TAKEAWAY","Take-away"Typos and spelling mistakes:
"Coffe"vs"Coffee"Whitespace and casing issues:
" In-store "Numeric formatting variations:
"$4.00","4,00"," 4.0 "Multiple coding systems:
"Credit Card"vs"CC"vs"card"
Café dataset: inconsistent Location labels#
df["Location"].value_counts(dropna=False)
You might see variants like "In-store", "Instore", "In store", "In-store ", "in-store".
Café dataset: inconsistent Payment Method labels#
df["Payment Method"].value_counts(dropna=False).head(20)
Expect to see "Credit Card", "creditcard", "CREDIT CARD", "cc", "Cash", "CASH", " cash".
Normalizing a category (demonstration)#
loc_clean = (
df["Location"]
.astype(str)
.str.strip()
.str.lower()
.replace({
"in-store": "in_store",
"instore": "in_store",
"in store": "in_store",
"take away": "takeaway"
})
)
loc_clean.value_counts()
After this normalization, we get a much cleaner set of location categories.
Spotting malformed Item values#
df["Item"].value_counts(dropna=False).head(20)
Entries like "UNKNOWN" or odd spellings show up here as value-level inconsistencies.
FinTech analogy#
In a P2P payments dataset, payment_method might contain:
"CARD","Credit Card","credit","CC","debit","DC""Apple Pay","apple pay","ApplePay","Apple payy"
These are all value-level inconsistencies—schema is fine (they’re strings), but the symbols for the same concept are not consistent.
2.3 Semantic and Business-Logic Errors#
Some values pass type checks and even look syntactically clean—but violate business logic or common sense. These are semantic errors.
Characteristics#
Internal contradictions between columns.
Quantities or prices that are impossible or implausible.
Derived fields (like totals) that don’t match their inputs.
Time-related violations (e.g., future dates, negative durations).
Checking: Total Spent = Quantity × Price#
First, convert to numeric:
cafe = df.copy()
cafe["Quantity_num"] = pd.to_numeric(cafe["Quantity"], errors="coerce")
cafe["Price_num"] = pd.to_numeric(cafe["Price Per Unit"], errors="coerce")
cafe["Total_num"] = pd.to_numeric(cafe["Total Spent"], errors="coerce")
cafe["Computed_Total"] = cafe["Quantity_num"] * cafe["Price_num"]
Now compare recorded vs computed totals:
mask_valid = (
cafe["Quantity_num"].notna()
& cafe["Price_num"].notna()
& cafe["Total_num"].notna()
)
mismatch = mask_valid & ~np.isclose(
cafe["Total_num"],
cafe["Computed_Total"],
rtol=1e-6, atol=1e-6
)
cafe.loc[mismatch, ["Transaction ID", "Item", "Quantity_num",
"Price_num", "Total_num", "Computed_Total"]].head(10)
Rows here are semantic errors: all three fields are numeric, but the total contradicts the quantity and price.
Detecting impossible or implausible values#
# Negative or zero quantity (almost always invalid for a basic café sale)
cafe[cafe["Quantity_num"] <= 0].head()
# Suspiciously high prices (e.g., > $20 for a typical café menu)
cafe[cafe["Price_num"] > 20].head()
These are not type issues—they’re violations of domain knowledge.
FinTech analogy#
Common semantic errors in financial data include:
A transaction marked
"completed"with a negative amount that is not a refund or chargeback.A loan payment date earlier than the loan origination date.
A
"USD"transaction with an amount that clearly reflects a foreign-currency figure.In a P2P system,
sender_id == receiver_idwhen self-transfers should not exist.
All of these require business logic, not just formatting rules, to detect and correct.
2.4 Outliers: Statistical and Domain-Based#
Outliers are values that are extreme compared to the bulk of the data. They may be:
valid but rare events
edge cases in business processes
data-entry errors (e.g., missing decimal point)
fraud or anomalous behavior
system glitches (duplicates, replays)
Key point: Outliers are not automatically errors; they are flags that deserve attention.
Two perspectives on outliers#
Statistical outliers
Defined by deviation from the distribution (e.g., using IQR or z-scores).
Domain outliers
Defined by violating domain expectations (e.g., café drinks shouldn’t cost $500).
Café dataset: summary statistics#
cafe[["Quantity_num", "Price_num", "Total_num"]].describe()
This gives us a sense of the typical ranges and potential extremes.
Visualizing outliers with a boxplot#
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
cafe["Total_num"].plot(kind="box")
plt.title("Boxplot of Total Spent")
plt.ylabel("Amount")
plt.show()
Points far above the upper whisker are statistical outliers.
IQR-based outlier detection#
q1 = cafe["Total_num"].quantile(0.25)
q3 = cafe["Total_num"].quantile(0.75)
iqr = q3 - q1
lower_bound = q1 - 1.5 * iqr
upper_bound = q3 + 1.5 * iqr
outliers = (cafe["Total_num"] < lower_bound) | (cafe["Total_num"] > upper_bound)
cafe.loc[outliers, ["Transaction ID", "Item", "Quantity_num",
"Price_num", "Total_num"]].head(10)
These rows might represent:
genuine large catering orders (valid extremes),
typos (e.g., 40.0 typed as 400), or
suspicious activity (if we extend to a financial setting).
FinTech analogy#
Outliers are especially important in FinTech:
Very large P2P transfers may indicate business accounts, wealth transfers, or money laundering.
Highly frequent low-value transactions could be bot activity or fraud testing cards.
Large negative balances might reflect errors, chargebacks, or leveraged positions.
How we treat outliers—remove, cap, segment, or keep—depends on whether they are errors, rare-but-valid events, or signals of behavior we care about.
2.5 Why These Categories Matter#
Each category naturally leads to different cleaning strategies (to be developed in later sections):
Type of Problem |
Typical Response |
|---|---|
Schema-level inconsistency |
Type coercion, schema enforcement |
Value-level inconsistency |
Standardization and normalization of categories |
Semantic/business-logic error |
Domain-rule checks, reconstruction, correction |
Outlier |
Investigation, special handling, or segmentation |
Misclassifying these problems can lead to over-cleaning (removing real, important data) or under-cleaning (keeping values that undermine analysis). The rest of the chapter builds on this taxonomy to diagnose and handle inconsistencies systematically in both the café data and the P2P payments data.
Diagnosing Inconsistency#
Diagnosing inconsistent data is a fundamental step in data cleaning. Before we can correct inconsistencies, we must be able to recognize them, characterize them, and distinguish harmless variation from true errors.
Diagnosis relies on a combination of:
thinking like a computer (types, schemas, parsing)
thinking like an analyst (distributions, unusual values)
thinking like a domain expert (business logic, plausibility)
This section demonstrates diagnostic techniques using the dirty café dataset, which contains schema issues, inconsistent categories, logical contradictions, and outliers. Each diagnostic method demonstrated here will later reappear when we apply them to the more complex P2P payments case study.
Assume the dataset is already loaded:
df = pd.read_csv("resources/data/dirty_cafe_sales.csv")
3.1 Understanding the Intended Schema#
You cannot diagnose inconsistencies without first knowing what should be in each column. The intended schema provides expectations for types, formats, and valid ranges.
Example expected schema for café data#
Column |
Expected Type |
Notes |
|---|---|---|
|
string |
unique |
|
category |
small controlled vocabulary |
|
integer > 0 |
no negatives or zeros |
|
float > 0 |
typical café prices |
|
float ≥ 0 |
should equal Quantity × Price |
|
category |
small set of values |
|
category |
typically “In-store” or “Takeaway” |
|
datetime |
valid café operating period |
But what does our dataset actually contain?#
df.dtypes
Common issues revealed:
numeric columns stored as
objectinconsistent date formats
mixed types in category fields
Diagnosing schema drift via type coercion#
Attempt coercion and inspect failures:
pd.to_numeric(df["Quantity"], errors="coerce").isna().sum()
pd.to_datetime(df["Transaction Date"], errors="coerce").isna().sum()
Rows that fail type coercion contain schema-level inconsistencies.
FinTech analogy#
Before validating a P2P payments dataset, you would define expectations for:
amount types (float, positive for completed payments)
timestamps (ISO8601)
currency formats
user IDs (consistent casing and length)
Schema validation is the first line of defense in any financial data operation.
3.2 Normalizing Error Tokens#
Inconsistent datasets often contain non-standard representations of invalid or missing values: "ERROR", "?", "UNKNOWN", "--", "N/A", etc. These tokens prevent meaningful diagnosis unless normalized.
Find potential error tokens#
for col in ["Item", "Payment Method", "Location", "Total Spent"]:
print(col)
print(df[col].astype(str).value_counts().head(10))
print()
If you see "ERROR" or "UNKNOWN" mixed in with valid categories, that is a red flag.
Normalize these tokens#
ERR_TOKENS = ["ERROR", "UNKNOWN", "N/A", "NA", "--", "??", " "]
df_norm = df.replace(ERR_TOKENS, np.nan)
Why normalize early?#
Because error tokens masquerading as valid strings obscure the true level of inconsistency. Just like we normalized missingness, normalization is the foundation for any consistency analysis.
FinTech analogy#
In transaction logs from banks or payment networks, "UNK", "null", and "999999" might represent invalid or placeholder values. These tokens must be recognized before diagnosing true inconsistencies.
3.3 Type Diagnosis and Parsing Challenges#
Even after normalization, columns may contain mixed-type values or formatting inconsistencies.
Diagnose via coercion#
quantity_parsed = pd.to_numeric(df_norm["Quantity"], errors="coerce")
quantity_parsed.isna().sum()
Rows where coercion fails likely contain:
non-numeric strings
stray punctuation
multiple numeric formats
Diagnose date inconsistencies#
parsed_dates = pd.to_datetime(df_norm["Transaction Date"], errors="coerce")
bad_dates = df_norm.loc[parsed_dates.isna(), "Transaction Date"].head(10)
bad_dates
These irregularities may reflect:
different upstream systems
user input error
system glitches during export
A helpful technique: sample the most suspicious rows#
df_norm.loc[parsed_dates.isna()].sample(5, random_state=42)
3.4 Categorical Profiling#
Categorical fields—like Item, Payment Method, Location—are especially prone to inconsistency because humans and systems tend to invent new label variants over time.
Explore category distributions#
df_norm["Location"].value_counts(dropna=False)
This will typically reveal:
casing differences
whitespace differences
synonyms
unexpected categories
placeholder values now normalized to
NaN
Detecting rare or suspicious values#
df_norm["Item"].value_counts().tail(10)
Rare categories at the tail may represent typos or mislabeling.
Visualizing categories#
df_norm["Payment Method"].value_counts().plot(kind="bar", figsize=(8,4))
Outlying categories (e.g., "creditcard" appearing once) are likely inconsistencies.
FinTech analogy#
In payment systems, category drift is extremely common:
"CARD", "card", "credit", "Credit Card", "CC", "CRD"
Without profiling, such drift silently corrupts downstream analysis of payment method adoption, fraud patterns, etc.
3.5 Logical Consistency Checks#
These checks detect inconsistencies that cannot be discovered by type or category profiling alone. They rely on relationships between fields.
Example: recompute Total Spent#
df_num = df_norm.copy()
df_num["Quantity_num"] = pd.to_numeric(df_num["Quantity"], errors="coerce")
df_num["Price_num"] = pd.to_numeric(df_num["Price Per Unit"], errors="coerce")
df_num["Total_num"] = pd.to_numeric(df_num["Total Spent"], errors="coerce")
df_num["Computed_Total"] = df_num["Quantity_num"] * df_num["Price_num"]
Find mismatches#
mask_computable = (
df_num["Quantity_num"].notna()
& df_num["Price_num"].notna()
)
mismatch = (
mask_computable
& df_num["Total_num"].notna()
& ~np.isclose(df_num["Total_num"], df_num["Computed_Total"], atol=1e-6)
)
df_num.loc[mismatch, ["Transaction ID", "Item", "Quantity_num",
"Price_num", "Total_num", "Computed_Total"]].head(10)
This reveals errors such as:
miscomputed totals
truncated decimals
corrupted values (
"ERROR"that becameNaN)
Check business-rule constraints#
df_num[df_num["Quantity_num"] <= 0].head()
df_num[df_num["Price_num"] > 20].head()
These rows violate domain knowledge: negative quantity or café prices > $20.
FinTech analogy#
Logical consistency checks are critical in financial datasets:
A completed transaction cannot have a negative amount unless it’s a refund.
A refund must flip the sign of the original transaction.
A user cannot send money to themselves (unless the platform allows self-transfers).
amountandcurrencymust match the region or payment rail.
3.6 Outlier Detection#
Outliers may represent valid but rare events—or serious inconsistencies.
Quick statistical summary#
df_num[["Quantity_num", "Price_num", "Total_num"]].describe()
Visualizing outliers#
import matplotlib.pyplot as plt
plt.figure(figsize=(6,4))
df_num["Total_num"].plot(kind="box")
plt.title("Boxplot of Total Spent")
plt.show()
Large deviations suggest outliers.
IQR-based rule#
q1 = df_num["Total_num"].quantile(0.25)
q3 = df_num["Total_num"].quantile(0.75)
iqr = q3 - q1
lower = q1 - 1.5*iqr
upper = q3 + 1.5*iqr
outliers = df_num[(df_num["Total_num"] < lower) | (df_num["Total_num"] > upper)]
outliers.head()
These outliers require interpretation, not automatic deletion.
FinTech analogy#
Outliers in financial data can indicate:
fraud
operational errors
laundering patterns
rare legitimate high-value transactions
The role of outliers in analysis depends on both statistics and domain knowledge.
3.7 Summary of Diagnostic Techniques#
Diagnosing inconsistency involves:
Checking schema alignment
Normalizing error tokens
Testing type coercion
Profiling category distributions
Applying logical consistency rules
Detecting statistical and domain outliers
This diagnostic toolkit prepares us for the next section, where we explore why inconsistencies arise and how to address them.
Causes of Inconsistency and Error**#
Inconsistent or erroneous data does not arise randomly. It is the product of real processes—human, technical, or business-driven—that shape how information enters a system. Understanding these causes is essential for diagnosing problems accurately and selecting the right cleaning strategies. A value that looks wrong may be perfectly valid given the business context, while a value that looks reasonable may hide a deeper process failure.
In FinTech especially, data inconsistencies often originate from the interplay of multiple systems: payment processors, internal ledgers, mobile apps, third-party APIs, batch jobs, and human inputs. The same concepts apply to our café dataset, which provides a simplified view of these broader dynamics.
4.1 Human Data Entry Errors#
Any system that involves manual input—cashiers, baristas, customer-facing forms—is vulnerable to human error.
Common forms#
Typographical errors (
"Coffe"instead of"Coffee")Mis-clicks or incorrect menu selection
Extra zeros (
200instead of20)Misplaced decimal points (
3instead of3.00, or30instead of3.0)Forgetting to fill out a field (later recorded as
""or"UNKNOWN")
Café dataset examples#
Look at some rare or unusual category values:
df["Item"].value_counts().tail(10)
Rare categories often include typos or unintended variants.
Check for impossible human-created numeric values:
df_num[df_num["Quantity_num"] > 100] # extremely unlikely in a café
Outlier quantities like 200 cookies are often simple keying mistakes.
FinTech analogy#
Customer service agents entering reference notes, merchants entering descriptor codes, or users manually editing memos can create typos that propagate into transaction data.
4.2 System Integration Issues#
Many datasets are assembled from multiple upstream systems—each with its own schema, formatting, and operational quirks. When integrated, these systems can produce inconsistent data.
Common forms#
Different date formats across systems
Price values sent as strings by one API and numerics by another
Case variations (
"Takeaway"vs"takeaway"vs"TAKE AWAY")Missing fields during API outages or degraded service
Legacy systems generating placeholder codes (e.g.,
"UNK","999999")
Café dataset example: inconsistent location formats#
df["Location"].value_counts(dropna=False)
Variants like "In-store", "In store", "Instore", "in store" suggest that different systems—or versions of the same system—used different conventions.
FinTech analogy#
When transaction data flows through card networks, processors, mobile apps, and internal accounting systems, each transformation stage can:
reformat timestamps
change the casing or value of
payment_methoddrop optional fields
introduce alignment issues or misencoded characters
Such inconsistencies are a normal side-effect of heterogeneous systems.
4.3 Business-Process Logic#
Some inconsistencies stem not from errors but from special business scenarios that create legitimate exceptions—or from business processes that do not enforce strict rules.
Examples of business-driven inconsistencies#
A café offering a promotion that overrides the usual price logic
A “free drink” reward causing
Price Per Unit = 0Modeling errors introduced by discounts or loyalty redemptions
Items with multiple sizes or variants recorded inconsistently
Café dataset example: totals that don’t match quantity × price#
df_num.loc[mismatch, ["Item", "Quantity_num", "Price_num",
"Total_num", "Computed_Total"]].head(10)
While many mismatches are errors, some could reflect:
combo deals
promotional discounts
manual adjustments at the register
So not all mismatches are errors; some reflect omitted business logic.
FinTech analogy#
Legitimate business-process differences include:
waived fees for premium users (sometimes left blank or set to zero)
partial refunds that appear as negative but do not correspond 1-to-1 with original amounts
multi-currency conversions that create rounding differences
chargebacks that reverse previous transactions but may not mirror the original structure
To clean this kind of data correctly, one must understand the underlying business workflows.
4.4 Fraud, Abuse, and Adversarial Behavior#
Some inconsistencies are not accidental—they are signals. Both cafés and financial platforms experience anomalous patterns that arise from misuse or bad actors.
Common forms#
Suspiciously large or repetitive transactions
Attempts to bypass validation (e.g., using
"N/A"or"--"as name fields)Timestamp manipulation
Self-transfers (in systems that prohibit them)
Rapid sequences of small transactions (fraud testing)
Café dataset example#
Large total amounts or extremely high quantities are not always errors:
outliers = df_num[df_num["Total_num"] > df_num["Total_num"].quantile(0.99)]
outliers.head()
Some could be catering orders; others might be anomalous behavior.
FinTech analogy#
Adversarial behavior often manifests as:
unusually structured transaction patterns
inconsistent metadata
impossible device or location changes
malformed identifiers designed to confuse systems
In these contexts, outliers and inconsistencies may be exactly the data you want to keep.
4.5 Pure Statistical Extremes#
Not all outliers or unusual values indicate mistakes. Some datasets naturally contain rare or heavy-tailed behaviors.
Legitimate but extreme values#
A customer ordering 25 pastries for an office meeting
A once-a-year holiday sales spike
A special seasonal item priced differently
Café dataset example#
df_num["Total_num"].describe()
Transactions in the top 1% may be perfectly valid events—labeling them as errors would distort the data and hide interesting patterns.
FinTech analogy#
Financial data often follows heavy-tailed distributions:
wealth transfers
loan balances
cryptocurrency transaction sizes
merchant payout volumes
These extremes are not errors—they are inherent to the domain.
4.6 Why Understanding Causes Matters#
Two values may look equally “wrong” in a dataset, yet require completely different treatments:
A typo should be corrected or imputed.
A system-integration artifact should be standardized.
A business-rule exception should be preserved.
A fraud pattern should be flagged, not cleaned.
A legitimate outlier should be neither removed nor overwritten.
Understanding why an inconsistency arises guides the decisions we make in how to handle it. The next section will connect these causes to practical cleaning strategies.
Strategies for Handling Inconsistency#
Once inconsistencies have been identified and their causes understood, the next step is deciding how to handle them. Not all inconsistencies should be corrected in the same way, and some should not be “fixed” at all. In financial datasets especially, over-cleaning can erase meaningful signals—such as fraud patterns or system-integration issues—while under-cleaning can distort metrics, bias models, or violate regulatory reporting requirements.
This section presents the main strategies for addressing inconsistent data, using examples from the café dataset. Later, we will apply these strategies comprehensively to the P2P payments dataset in the case study.
5.1 Type Correction and Enforcement#
Many inconsistencies originate from incorrect or mixed types. Type correction is often the first cleaning step because it enables more accurate detection of deeper issues.
Approach#
Convert numeric columns using
pd.to_numeric(errors="coerce").Convert date fields with
pd.to_datetime(errors="coerce").Investigate values that fail conversion—these often reveal hidden errors.
Example: enforcing numeric types#
cafe = df_norm.copy()
cafe["Quantity_num"] = pd.to_numeric(cafe["Quantity"], errors="coerce")
cafe["Price_num"] = pd.to_numeric(cafe["Price Per Unit"], errors="coerce")
cafe["Total_num"] = pd.to_numeric(cafe["Total Spent"], errors="coerce")
cafe[["Quantity_num", "Price_num", "Total_num"]].head()
Values that become NaN after coercion signal earlier schema or value-level inconsistencies.
Example: enforcing datetime types#
cafe["Date_parsed"] = pd.to_datetime(cafe["Transaction Date"], errors="coerce")
cafe["Date_parsed"].isna().sum()
Rows with unparseable dates may require standardization, correction, or removal.
FinTech analogy#
In payments data:
Transaction amounts must be numeric.
Timestamps must be valid and time-zone aligned.
Currency codes must conform to ISO-4217.
Type enforcement is usually step one in any FinTech ETL pipeline.
5.2 Standardizing Categorical Data#
Many inconsistencies arise in categorical fields due to casing differences, whitespace, typos, or synonym drift across systems. Standardization ensures that logically identical values are treated equivalently.
Common techniques#
Lowercase/case-folding
Stripping whitespace
Normalizing punctuation
Mapping synonyms to canonical forms
Collapsing rare categories into
"Other"
Example: normalizing Location#
cafe["Location_clean"] = (
cafe["Location"]
.astype(str)
.str.strip()
.str.lower()
.replace({
"in-store": "instore",
"in store": "instore",
"instore ": "instore",
"take away": "takeaway"
})
)
cafe["Location_clean"].value_counts()
Example: normalizing Payment Method#
PAYMENT_MAP = {
"credit card": "card",
"creditcard": "card",
"cc": "card",
"debit": "card",
"cash ": "cash",
"cash": "cash",
"cashm": "cash" # hypothetical typo
}
cafe["Payment_clean"] = (
cafe["Payment Method"]
.astype(str)
.str.strip()
.str.lower()
.replace(PAYMENT_MAP)
)
FinTech analogy#
Payment methods, merchant categories, and transaction statuses often require normalization:
"Credit Card" → "card", "FAILED" → "failed", "ChargeBack" → "chargeback"
Without normalization, aggregation becomes meaningless.
5.3 Correcting Logical Errors and Reconstructing Values#
Some inconsistencies cannot be solved by formatting—they require applying domain rules to detect and correct them.
Typical corrections#
Recompute derived fields
Validate cross-field relationships
Replace impossible values
Apply domain constraints (e.g., minimum and maximum prices)
Example: recomputing Total Spent#
mask_missing_total = cafe["Total_num"].isna()
mask_have_components = cafe["Quantity_num"].notna() & cafe["Price_num"].notna()
reconstruct = mask_missing_total & mask_have_components
cafe.loc[reconstruct, "Total_num"] = (
cafe.loc[reconstruct, "Quantity_num"] * cafe.loc[reconstruct, "Price_num"]
)
Correcting inconsistent totals#
mask_inconsistent = (
cafe["Total_num"].notna()
& cafe["Computed_Total"].notna()
& ~np.isclose(cafe["Total_num"], cafe["Computed_Total"], atol=1e-6)
)
cafe.loc[mask_inconsistent, "Total_num"] = cafe.loc[mask_inconsistent, "Computed_Total"]
Example: fixing implausible prices#
mask_bad_prices = (cafe["Price_num"] < 0.5) | (cafe["Price_num"] > 20)
cafe.loc[mask_bad_prices, ["Item", "Price_num"]].head()
A domain-informed fix might set these to NaN, impute typical prices, or drop the rows entirely.
FinTech analogy#
In payment data:
A “completed” transaction with a negative amount is a semantic error.
A chargeback must reverse the sign of the original transaction.
A timestamp earlier than account creation is invalid.
A transaction in USD cannot have an amount formatted like
€12,34.
Logical corrections often require understanding the business.
5.4 Outlier Treatment#
Outliers can be legitimate or problematic. The goal is not merely to remove them, but to classify and treat them appropriately.
Strategies#
Remove (if clear error)
Cap/Winsorize (preserve distribution shape while limiting extremes)
Transform (e.g., log scaling)
Segment (treat as special cases rather than errors)
Flag (preserve values but record their unusualness)
Example: identifying statistical outliers#
q1 = cafe["Total_num"].quantile(0.25)
q3 = cafe["Total_num"].quantile(0.75)
iqr = q3 - q1
upper = q3 + 1.5*iqr
lower = q1 - 1.5*iqr
outliers = cafe[(cafe["Total_num"] < lower) | (cafe["Total_num"] > upper)]
outliers.head()
Example: capping extreme total values#
cafe["Total_capped"] = cafe["Total_num"].clip(lower, upper)
FinTech analogy#
Outliers can indicate:
fraud
operational anomalies
high-net-worth transfers
merchant settlement events
Removing outliers blindly can erase the very signals analysts or regulators care about.
5.5 When to Leave Data As-Is#
Not all inconsistencies should be altered. Some reflect:
rare but valid behavior
regulatory or operational requirements
special transaction types
business promotions or exceptions
fraud patterns that must be preserved for analysis
Examples in café data#
A legitimate bulk order may look like an outlier but should not be removed.
Rounding behavior (e.g., \(3.995 → \)4.00) may create small mismatches worth keeping.
FinTech analogy#
Many financial anomalies are meaningful:
A sudden high-value transfer could be part of wealth movement.
A large cluster of microtransactions may indicate fraud testing.
A missing field may correlate with user behavior (e.g., users skipping memos).
In cleaning financial data, the safest strategy is often “flag, don’t overwrite.”
5.6 Documentation and Auditability#
Any modification to raw data should be documented, reproducible, and reversible. This is especially important in regulated domains.
Best practices#
Track all transformations in code, not ad hoc.
Maintain original columns alongside cleaned ones (e.g.,
amount_raw → amount_clean).Add indicator flags (e.g.,
was_price_outlier,was_total_recomputed).Log rows dropped during cleaning.
Version datasets after each processing stage.
Example: adding diagnostic flags#
cafe["was_total_inconsistent"] = mask_inconsistent.astype(int)
cafe["was_price_outlier"] = mask_bad_prices.astype(int)
FinTech analogy#
Auditability is required for:
AML reports
lending decisions
fraud analysis escalations
dispute resolution
model governance (e.g., for credit scoring)
A cleaned dataset with unclear lineage is unacceptable in production FinTech systems.
Summary of Strategy Mapping#
Inconsistency Type |
Recommended Strategy |
|---|---|
Schema-level errors |
Type coercion, schema enforcement |
Value-level inconsistencies |
Standardization (case, whitespace, synonyms) |
Semantic/business-logic errors |
Rule-based corrections, reconstruction |
Outliers |
Investigation, capping, segmentation, or flagging |
Special cases |
Leave as-is, but annotate |
All modifications |
Document and preserve lineage |
Evaluating the Impact of Cleaning Decisions#
Cleaning inconsistent data is not simply a mechanical task. Every transformation — type coercion, category normalization, outlier treatment, value reconstruction — changes the dataset. Those changes can be beneficial, removing noise and errors, or detrimental, introducing bias, collapsing meaningful variation, or obscuring important patterns.
In FinTech settings, the stakes are especially high: data cleaning choices can influence fraud detection alerts, regulatory compliance metrics, revenue reporting, and credit decisions. Therefore, evaluating the impact of cleaning decisions is essential.
In this section, we focus on three major aspects of evaluation:
Distributional changes
Changes in relationships and structure
Impacts on business metrics and downstream analysis
We continue with the café dataset (df_norm and cafe) as our running example.
Online commerce now operates at a scale and speed that traditional fraud-prevention methods were never designed to support. Every card-not-present transaction—whether it’s a subscription purchase, a mobile-app payment, or an e-commerce checkout—carries the risk of a stolen identity or compromised account. Fraud patterns adapt rapidly, attacker tools evolve, and the sheer volume of global payment traffic amplifies both the opportunity and impact of fraud.
To keep up, payment processors increasingly rely on machine learning. Stripe’s Radar system is one well-documented example of this broader industry shift: public engineering posts describe how Radar evaluates hundreds of real-time signals for every transaction and updates its risk scoring as fraud behavior changes. These accounts also underscore challenges faced across the payments ecosystem—balancing fraud prevention with customer experience, reducing false positives, and maintaining explainable, auditable decision-making. Stripe: Machine Learning/Fraud Detection
This example is not about a single company—it illustrates a larger truth about modern financial systems: data science is now essential to managing risk, protecting customers, and enabling trustworthy digital transactions at scale.
Data science is an interdisciplinary field that uses scientific methods, computational tools, and domain expertise to extract insight from structured and unstructured data. By integrating mathematics, statistics, computer science, and subject-matter knowledge, it blends statistical reasoning, algorithmic techniques, and machine learning to uncover patterns that support informed decision-making. As organizations increasingly view data as a strategic asset, data science has become essential across industries by providing a systematic framework for transforming raw data into meaningful knowledge that shapes decisions and drives innovation.
In finance, data science plays a transformative role, powering algorithmic trading, fraud detection, credit scoring, robo-advisory platforms, RegTech applications, blockchain analytics, and real-time risk management.Online commerce now operates at a scale and speed that traditional fraud-prevention methods were never designed to support. Every card-not-present transaction—whether it’s a subscription purchase, a mobile-app payment, or an e-commerce checkout—carries the risk of a stolen identity or compromised account. Fraud patterns adapt rapidly, attacker tools evolve, and the sheer volume of global payment traffic amplifies both the opportunity and impact of fraud.
To keep up, payment processors increasingly rely on machine learning. Stripe’s Radar system is one well-documented example of this broader industry shift: public engineering posts describe how Radar evaluates hundreds of real-time signals for every transaction and updates its risk scoring as fraud behavior changes. These accounts also underscore challenges faced across the payments ecosystem—balancing fraud prevention with customer experience, reducing false positives, and maintaining explainable, auditable decision-making. Stripe: Machine Learning/Fraud Detection
This example is not about a single company—it illustrates a larger truth about modern financial systems: data science is now essential to managing risk, protecting customers, and enabling trustworthy digital transactions at scale.
Data science is an interdisciplinary field that uses scientific methods, computational tools, and domain expertise to extract insight from structured and unstructured data. By integrating mathematics, statistics, computer science, and subject-matter knowledge, it blends statistical reasoning, algorithmic techniques, and machine learning to uncover patterns that support informed decision-making. As organizations increasingly view data as a strategic asset, data science has become essential across industries by providing a systematic framework for transforming raw data into meaningful knowledge that shapes decisions and drives innovation.
In finance, data science plays a transformative role, powering algorithmic trading, fraud detection, credit scoring, robo-advisory platforms, RegTech applications, blockchain analytics, and real-time risk management.#
6.1 Evaluating Distributional Shifts#
Cleaning often alters the distribution of numeric or categorical variables. Some shifts are desirable (removing spurious spikes caused by bad data), while others can introduce bias (e.g., capping outliers too aggressively).
Example: comparing total-spent distribution before and after cleaning#
Suppose we earlier reconstructed inconsistent totals or capped extreme values. Here’s how we can visualize the effect:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
df_num["Total_num"].plot(kind="hist", bins=40, ax=ax[0], title="Original Total Spent")
cafe["Total_num"].plot(kind="hist", bins=40, ax=ax[1], title="Cleaned Total Spent")
plt.tight_layout()
plt.show()
What to look for#
Are extreme values removed or reduced?
Did the center of the distribution shift?
Did cleaning create artificial spikes (e.g., replacing many values with the same fallback)?
Did capping compress the tail too much?
FinTech analogy#
Distribution shifts matter because they can distort:
revenue or balance estimates
fraud thresholds
creditworthiness indicators
risk modeling inputs
Subtle biases introduced during cleaning can propagate downstream.
6.2 Evaluating Changes in Relationships#
Cleaning can also change correlations, logical relationships, and model-relevant structure.
Example: relationship between Total Spent and Quantity × Price#
Before cleaning, we may have inconsistencies:
df_num[["Quantity_num", "Price_num", "Total_num"]].corr()
After cleaning:
cafe[["Quantity_num", "Price_num", "Total_num"]].corr()
You should observe:
Stronger correlations after correction
Reduced noise from erroneous totals
Better alignment between dependent and independent fields
Example: detecting structural changes#
Suppose we standardized Location and Payment Method. We can check whether cleaning altered category proportions:
pd.DataFrame({
"before": df_norm["Location"].value_counts(normalize=True),
"after": cafe["Location_clean"].value_counts(normalize=True)
})
Questions to ask#
Did we accidentally merge categories that were actually distinct?
Did normalization reduce the number of unique values appropriately?
Did we lose meaningful business segments?
FinTech analogy#
In financial datasets, cleaning may:
reduce correlation between user features and transaction behavior
remove or distort seasonality patterns
collapse fraud-related signals into generic categories
alter network relationships between senders and receivers
Evaluating these effects is essential for trustworthy modeling.
6.3 Evaluating Impact on Business Metrics#
In real organizations, cleaning is not just about improving the dataset — it affects core business metrics. A cleaning decision that looks harmless statistically may materially alter operational or financial reporting.
Example: how many transactions were removed?#
rows_before = len(df_norm)
rows_after = len(cafe)
rows_before, rows_after, rows_before - rows_after
Dropping too many rows, especially systematically biased ones, can skew metrics.
Example: effect on total revenue#
original_rev = df_num["Total_num"].sum(skipna=True)
cleaned_rev = cafe["Total_num"].sum(skipna=True)
original_rev, cleaned_rev, cleaned_rev - original_rev
Differences may come from:
reconstructed totals
removed extreme values
corrected price logic
dropping inconsistent rows
Evaluating categorical shifts#
original_pm = df_norm["Payment Method"].value_counts()
cleaned_pm = cafe["Payment_clean"].value_counts()
pd.DataFrame({"before": original_pm, "after": cleaned_pm}).fillna(0)
Changing category definitions (e.g., "CC" → "card") may alter the reported share of payment methods.
FinTech analogy#
Business metrics sensitive to cleaning include:
total payment volume (TPV)
number of failed transactions
chargeback rate
average transaction amount
AML rule hit-rates
revenue from fees
Cleaning must be evaluated not just for correctness but for financial impact.
6.4 Sensitivity Analyses and “What-If” Scenarios#
Since many cleaning decisions involve judgment calls, it is critical to test how robust your results are to reasonable alternatives.
Example: testing two different outlier thresholds#
def cap_total(df, k):
q1 = df["Total_num"].quantile(0.25)
q3 = df["Total_num"].quantile(0.75)
iqr = q3 - q1
lower = q1 - k*iqr
upper = q3 + k*iqr
return df["Total_num"].clip(lower, upper)
cafe["Total_cap_1_5"] = cap_total(cafe, 1.5)
cafe["Total_cap_3_0"] = cap_total(cafe, 3.0)
Compare outcomes#
cafe[["Total_cap_1_5", "Total_cap_3_0"]].describe()
Interpretation#
A stricter threshold (1.5×IQR) may distort the real distribution.
A looser threshold (3×IQR) may preserve legitimate high-value behavior.
FinTech analogy#
Sensitivity analysis is standard in:
stress testing
credit loss modeling
fraud alert calibration
AML thresholds
regulatory metric validation
Cleaning choices should be tested for robustness before use in production or high-stakes analysis.
6.5 Guidelines for Responsible Evaluation#
Never assume your cleaning improves the data—verify it.
Preserve both raw and cleaned versions to enable comparison.
Evaluate changes at three levels:
values → distributions → relationships → business metrics
Document assumptions (e.g., outlier threshold choices, rule-based logic).
Seek domain expertise—not everything that looks wrong is wrong.
Use flags rather than destructive edits for reversible workflows.
Check for unintended side effects (e.g., distortions in category proportions).
Validate cleaning decisions across multiple analytical tasks (summary statistics, classification, forecasting, fraud detection).
Evaluation is not an afterthought—it is central to trustworthy data science, especially in regulated industries.
6.6 Summary#
Cleaning inconsistent data is powerful but consequential. Evaluating the effects of those decisions ensures that:
errors are corrected,
legitimate variation remains intact,
business meaning is preserved, and
analyses remain valid and reproducible.
In the next section, we bring all these ideas together in a full case study using the P2P payments dataset. This demonstrates how diagnosis, cleaning, and evaluation work in a realistic FinTech setting.
Case Study: Cleaning Inconsistencies and Outliers in a P2P Payments Dataset**#
In this case study, we apply the full inconsistency-cleaning workflow to a synthetic—but realistic—peer-to-peer payments dataset. Unlike the café dataset, which allowed us to build intuition with simple business logic, this dataset more closely reflects the challenges encountered in real financial systems:
multiple upstream systems generating slightly different field formats
inconsistent categorical values
malformed or ambiguous numeric values
timestamps with errors or drift
semantic contradictions (e.g., completed transactions with negative amounts)
true behavioral variation mixed with noise
outliers that could be errors, fraud, or legitimate large transfers
Our goal is not to produce a perfectly clean dataset, but to demonstrate a principled, traceable workflow that respects both data quality and business context.
Assume the dataset has been loaded:
import pandas as pd
import numpy as np
df = pd.read_csv("resources/data/dirty_p2p_payments.csv")
df.head()
7.1 Schema Validation and Initial Profiling#
Before cleaning individual inconsistencies, we must understand what the dataset should look like.
Expected schema#
Column |
Expected Type |
Notes |
|---|---|---|
|
string |
unique identifier |
|
string |
user identifier |
|
string |
user identifier |
|
numeric |
may require parsing |
|
category |
ISO-4217 codes (USD, EUR, etc.) |
|
category |
small controlled vocabulary |
|
category |
completed, failed, refunded, chargeback |
|
datetime |
parseable and within valid range |
|
string |
free-form text, may be empty |
Check inferred types#
df.dtypes
Typical issues you may see:
amountis anobjectbecause of$, commas, malformed strings.currencyincludes inconsistent or placeholder codes.payment_methodhas many variants.timestampis stored as a string across multiple formats.
Profile the data#
df.describe(include="all").transpose()
This provides an initial sense of structure, missingness, and value variability.
7.2 Normalizing Error Tokens and Enforcing Types#
Before deeper diagnostics, normalize common placeholder tokens for missing or invalid values.
Normalize error tokens#
ERR_TOKENS = ["", " ", "NA", "N/A", "UNKNOWN", "UNK", "null", "NULL", "--", "??"]
df_norm = df.replace(ERR_TOKENS, np.nan)
Parse numeric fields#
def parse_amount(x):
if pd.isna(x):
return np.nan
x = str(x).strip()
if x.startswith("$"):
x = x[1:]
if "," in x and "." not in x:
x = x.replace(",", ".")
try:
return float(x)
except ValueError:
return np.nan
df_norm["amount_num"] = df_norm["amount"].apply(parse_amount)
df_norm["amount_num"].isna().mean()
Parse timestamps#
df_norm["timestamp_parsed"] = pd.to_datetime(df_norm["timestamp"], errors="coerce", utc=True)
df_norm["timestamp_parsed"].isna().sum()
Rows that fail parsing indicate inconsistent or malformed timestamps.
7.3 Standardizing Categories#
Categorical standardization reduces drift and makes inconsistencies visible.
Normalize payment_method#
pm = (
df_norm["payment_method"]
.astype(str).str.strip().str.lower()
.replace({
"credit card": "card",
"cc": "card",
"debit": "card",
"apple pay": "applepay",
"apple payy": "applepay",
"google pay": "googlepay",
"gpay": "googlepay",
"venom": "venmo" # typo
})
)
df_norm["payment_method_std"] = pm
df_norm["payment_method_std"].value_counts()
Normalize currency#
df_norm["currency_std"] = (
df_norm["currency"]
.astype(str).str.strip().str.upper()
)
df_norm["currency_std"].value_counts()
ISO-4217 codes allow meaningful grouping.
Standardize transaction status#
df_norm["status_std"] = df_norm["status"].astype(str).str.lower().str.strip()
df_norm["status_std"].value_counts()
At this point, category-level inconsistencies have been surfaced and neutralized.
7.4 Logical Consistency Checks#
Now we check for semantic inconsistencies that violate business logic.
1. Negative amounts#
Negative transfers may be valid only for refunds or chargebacks.
negatives = df_norm[df_norm["amount_num"] < 0]
negatives["status_std"].value_counts()
If many negative amounts appear for "completed" transactions, that is a semantic error.
2. Status–Amount consistency#
mask_bad_completed = (
(df_norm["status_std"] == "completed") &
(df_norm["amount_num"] < 0)
)
df_norm.loc[mask_bad_completed, ["transaction_id", "amount_num", "status_std"]].head()
3. Sender–Receiver consistency#
Self-transfers may or may not be allowed.
self_transfers = df_norm[df_norm["sender_id"] == df_norm["receiver_id"]]
self_transfers.head()
If the system forbids self-transfers, these are errors.
4. Timestamp validity#
Check for future dates or implausible historical dates:
df_norm["timestamp_parsed"].describe()
Outliers indicate system drift or malformed input.
7.5 Outlier Detection#
Outliers in financial systems may indicate errors, fraud, customer segmentation differences, or special-use accounts.
Statistical outliers (IQR rule)#
q1 = df_norm["amount_num"].quantile(0.25)
q3 = df_norm["amount_num"].quantile(0.75)
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = df_norm[(df_norm["amount_num"] < lower) | (df_norm["amount_num"] > upper)]
outliers.head()
Business-outlier inspection#
Look for patterns in payment methods:
outliers["payment_method_std"].value_counts()
Or user-level behavior:
outliers["sender_id"].value_counts().head()
Large P2P outliers might be:
loan repayments
business-use accounts on a consumer platform
fraud attempts
legitimate high-value transfers
Domain knowledge drives treatment.
7.6 Cleaning Actions#
We now combine previous steps into a structured cleaning workflow.
Drop unusable rows#
df_clean = df_norm.copy()
df_clean["missing_count"] = df_clean.isna().sum(axis=1)
df_clean = df_clean[df_clean["missing_count"] <= 6] # threshold chosen for illustration
Fix semantic errors#
Correct negative amounts in "chargeback" or "refund" rows, but not in "completed" rows:
chargebacks = df_clean["status_std"].isin(["chargeback", "refunded"])
df_clean.loc[chargebacks & (df_clean["amount_num"] > 0), "amount_num"] *= -1
Standardize categories (as above)#
Already applied in Section 7.3.
Add diagnostic flags#
df_clean["was_negative"] = (df_clean["amount_num"] < 0).astype(int)
df_clean["was_unparsed_timestamp"] = df_clean["timestamp_parsed"].isna().astype(int)
df_clean["was_outlier"] = ((df_clean["amount_num"] < lower) |
(df_clean["amount_num"] > upper)).astype(int)
Output cleaned dataset#
df_clean.head()
We now have a version of the dataset that is:
type-consistent
category-normalized
semantically validated
with outliers flagged, not blindly removed
7.7 Evaluating the Impact of Cleaning#
As emphasized earlier, cleaning must be evaluated.
Distribution comparison#
df_norm["amount_num"].plot(kind="hist", bins=50, alpha=0.5, label="before")
df_clean["amount_num"].plot(kind="hist", bins=50, alpha=0.5, label="after")
plt.legend()
plt.show()
Effect on business metrics#
original_tpv = df_norm["amount_num"].sum(skipna=True)
cleaned_tpv = df_clean["amount_num"].sum(skipna=True)
original_tpv, cleaned_tpv, cleaned_tpv - original_tpv
Impact on category proportions#
pd.DataFrame({
"before": df_norm["payment_method_std"].value_counts(normalize=True),
"after": df_clean["payment_method_std"].value_counts(normalize=True)
})
Interpretation#
Look for:
shifts in transaction volume
removed or reclassified anomalies
artificially compressed distributions
changes in user segmentation
disappearance of meaningful patterns
If the cleaning erases meaningful variation (especially fraud patterns), it must be reconsidered.
Case Study Summary#
By applying the full inconsistency-cleaning workflow to the P2P payments dataset, we learned how to:
validate and understand an intended schema
normalize error tokens to reveal hidden inconsistencies
standardize categorical fields
detect semantic inconsistencies that violate payment-system logic
diagnose statistical and domain-specific outliers
apply corrective actions judiciously
preserve auditability through diagnostic flags
evaluate cleaning impacts on distributions and business metrics
This case study illustrates that cleaning inconsistency is not only a technical task but a conceptual and domain-driven exercise—a central theme in financial data analytics.
Chapter Summary#
Inconsistent data is not a special case or an anomaly—it is a fundamental characteristic of real-world datasets, especially in FinTech. In this chapter, we explored the many ways that data can be present but still wrong, illogical, or misleading. We developed a systematic framework for identifying, understanding, and addressing these issues, building on the concepts introduced in the earlier chapters on data quality and missingness.
We began by distinguishing four major categories of data problems:
Schema-level inconsistencies, where values violate intended data types or formats.
Value-level inconsistencies, such as casing differences, typos, stray punctuation, and multiple coding conventions.
Semantic or business-logic errors, where values pass type checks but contradict the relationships or rules inherent to the domain.
Outliers, which may be statistical anomalies, domain-specific extremes, mistakes, or intentional patterns (including fraud).
Using the café dataset, we demonstrated how these inconsistencies manifest in a simple transactional environment: misformatted prices, inconsistent category labels, miscomputed totals, and unusual quantities or amounts. These examples helped build intuition for diagnosing issues systematically before attempting to repair them.
We then explored the causes of inconsistent data, emphasizing that every error reflects some underlying process—human data entry, system integration drift, poorly implemented business logic, fraud or adversarial behavior, or legitimate but rare events. Understanding causation is key to determining the correct cleaning strategy.
This led into a structured set of strategies for handling inconsistencies, including:
enforcing types and schemas
standardizing categorical variables
correcting logical inconsistencies and reconstructing derived values
identifying, classifying, and treating outliers
and knowing when to leave data untouched
We concluded with guidance on evaluating the impact of cleaning decisions, a critical step often overlooked. Cleaning is not neutral: it changes distributions, correlations, category proportions, and business-critical metrics. Through visualization, metric comparisons, and sensitivity analysis, we emphasized how to ensure that cleaning improves data quality without hiding meaningful variation or introducing bias.
Finally, in the case study, we applied the full workflow—from diagnosis to correction to evaluation—to a synthetic P2P payments dataset that simulates the challenges of real FinTech systems. This included schema issues, formatting drift, inconsistent status–amount relationships, malformed timestamps, rare but important outliers, and subtle business-rule violations. Through this end-to-end example, students saw how concepts, tools, and judgment come together in a realistic cleaning task.
Together, the techniques and reasoning developed in this chapter provide the foundation for reliable, reproducible, and contextually informed data cleaning. Inconsistent data is not simply “messy”—it encodes the history of how the data was produced. By learning to diagnose and address inconsistencies with care, we prepare ourselves for the complex realities of analytical work in FinTech and beyond.
Exercises#
Conceptual Exercises#
9.1 Classifying Types of Inconsistency#
For each example below, classify the inconsistency as schema-level, value-level, semantic/business-logic error, or outlier. Briefly justify your answer.
a. Price Per Unit = "4,00" in a dataset expecting U.S. decimal notation.
b. A transfer of \(3,500 in a P2P dataset where most transactions range from \)5–$200.
c. A transaction marked "completed" with a negative amount.
d. A timestamp stored as "2023/13/05".
e. Payment method recorded as "CREDIT CRAD".
9.2 Diagnosing Causes#
Explain the most likely underlying cause for each inconsistency:
a. Multiple spelling variations of "Takeaway" in the café dataset.
b. A cluster of transactions with unparseable timestamps during the same 10-minute period.
c. Extremely large P2P transfers from a small set of sender IDs.
d. Total Spent values that differ slightly from Quantity × Price (e.g., off by a few cents).
e. A customer ordering a quantity of -3 coffees.
9.3 Strategy Selection#
For each situation, choose an appropriate strategy (type enforcement, standardization, reconstruction, outlier treatment, leave unchanged) and explain why:
a. A café order shows Price Per Unit = "$4.00".
b. A P2P transfer has status = "chargeback" but amount_num = +25.00.
c. Payment Method appears as "CASH", "cash", " Cash".
d. A café order totals $400 involving 50 pastries.
e. A single transaction has timestamp = "2028-01-01T00:00:00Z".
9.4 Reasoning About Outliers#
Describe when an outlier should:
a. be removed entirely b. be winsorized or capped c. be transformed (e.g., log scaling) d. remain untouched Give an example of each case drawn from either dataset.
Part 2 — Applied Exercises: Café Dataset#
Assume the café dataset is loaded as:
df = pd.read_csv("resources/data/dirty_cafe_sales.csv")
9.5 Type Enforcement Audit#
Coerce Quantity, Price Per Unit, and Total Spent to numeric.
Report:
how many values fail conversion in each column
what kinds of tokens appear in the failing rows
9.6 Categorical Profiling and Normalization#
Perform the following:
a. List all unique values (including whitespace variants) in Location and Payment Method.
b. Normalize these categories using:
lowercase conversion
whitespace stripping
mapping common variants to canonical forms c. Report how the number of unique values changes before and after cleaning.
9.7 Logical Consistency Check: Recomputing Totals#
a. Compute a derived column Computed_Total = Quantity × Price Per Unit.
b. Identify rows where Total Spent does not match the computed total.
c. Classify mismatches as:
likely data-entry error
likely discount/promotion
unclear d. Recompute totals only where appropriate, documenting your decisions.
9.8 Detecting and Interpreting Outliers#
Using Total Spent:
a. Identify statistical outliers using the IQR rule. b. Visualize outliers using a boxplot or histogram. c. Investigate whether high outliers correspond to:
legitimate large orders
implausible values
data-entry mistakes d. Decide how to treat them and justify your reasoning.
Part 3 — Applied Exercises: P2P Payments Dataset#
Assume the dataset is loaded as:
df = pd.read_csv("resources/data/dirty_p2p_payments.csv")
9.9 Schema Audit and Error Token Normalization#
a. Inspect inferred types for each column.
b. Identify columns stored as strings that should be numeric or datetime.
c. Normalize the placeholder tokens ("UNK", "N/A", "--", "??", etc.) to NaN.
d. Report how the missing-value counts change after normalization.
9.10 Parsing Amounts and Timestamps#
a. Clean and parse the amount column into a numeric amount_num.
b. Parse timestamp into a unified datetime format.
c. Identify rows where parsing fails and analyze common patterns (e.g., format issues, copy-paste errors, system bugs).
9.11 Categorical Standardization#
Standardize payment_method, currency, and status using:
lowercase normalization
whitespace removal
synonym mapping (e.g.,
"venom" → "venmo","credit card" → "card")
Report the number of categories before and after standardization.
9.12 Logical Consistency Checks#
a. Identify rows where:
status = "completed"butamount_num < 0status ∈ {"chargeback","refunded"}butamount_num > 0b. Detect self-transfers (sender_id == receiver_id). c. Identify transactions that appear in the future or far in the past.
Classify each inconsistency as:
likely system issue
likely data-entry issue
likely fraud/anomaly
unclear but suspicious
9.13 Outlier Exploration#
a. Identify amount outliers using IQR or z-score methods. b. Investigate outliers by:
sender ID
payment method
currency c. Hypothesize reasons for the outliers (loan repayments? errors? testing behavior?). d. Decide whether to keep, cap, drop, or flag them.
9.14 Execute a Full Cleaning Pipeline#
Perform the following steps:
Normalize error tokens
Enforce numeric and datetime types
Standardize categories
Correct semantic errors (e.g., inconsistent status/amount combinations)
Add diagnostic flags (
was_negative,was_outlier, etc.)Drop rows that are too incomplete or structurally corrupted
Produce a final cleaned dataset
Document each transformation clearly.
9.15 Evaluate Cleaning Impact#
Evaluate both before and after cleaning:
a. Total payment volume b. Distribution of amounts c. Proportion of each payment method d. Outlier prevalence e. Number of rows retained or removed
Write a short reflection addressing:
Which cleaning actions had the largest impact?
Were any unexpected patterns revealed?
How might these decisions affect downstream fraud detection or risk modeling?
Part 4 — Integrated Reflection#
9.16 Reflection: When Is “Cleaning” Too Much?#
Write a short essay (1–2 paragraphs) addressing:
Why it is dangerous to over-clean financial datasets
Examples where inconsistencies reflect meaningful behavior (e.g., fraud, refunds, business-user transfers)
How you would balance correctness with preserving signal in a real FinTech pipeline