Data wrangling: quality, cleansing and understanding data

After this lesson you will say what data quality means and why its conventional definition is not enough, place data wrangling in the data-science pipeline, and take a dirty record through parsing, correcting, standardizing, matching and consolidating — knowing why the steps come in that order.

The slides' example has two data sources. In the first, a contact is five lines of text, like an address label: "Beth Christine Parker, SLS MGR / Regional Port Authority / Federal Building / 12800 Lake Calumet / Hedgewisch, IL" (p. 1088). The second — call it the contact list — has "Ms. Elizabeth Christine Parker-Lewis, Regional Port Authority, Federal Building, 12800 S. Butler Dr., Suite 2, Chicago, IL 60633-2398", with a phone and a fax number (p. 1095).

One person or two? Compare the rows the way a database does, value by value: the first name differs, the surname differs, the street differs, the city differs. A query that counts the contacts counts two, and a mailing sends two letters.

The slides end this story with one record, richer than either row, and every change on the way is justified by a rule or a reference. That is the difference between wrangling data and "torturing" it — a word the slides use in a quotation with a problem of its own. By the end of the lesson you will know why no comparison of the raw rows could ever have found this duplicate, and what it took to find it.

Five words for good data, four reasons they are not enough

Before you can fix data you need a word for "good". The slide "Conventional Definition of Data Quality" (p. 1069) gives five, each a property of how the data was recorded. Read each next to a defect it rules out, in a contact list like the one of the hook.

The five dimensions of p. 1069 with the slide's definitions; the defects in the last column are ours.
DimensionThe slide's definitionA defect it rules out
Accuracy"The data was recorded correctly."Thomas Okafor is listed as sales manager; he runs purchasing.
Completeness"All relevant data was recorded."No phone number for a contact who gave one.
Uniqueness"Entities are recorded once."Beth Parker and Elizabeth Parker-Lewis: one person, two rows.
Timeliness"The data is kept up to date (and time consistency is granted)."An address from before the firm moved; open orders counted on Monday, payments on Friday, so the two never add up.
Consistency"The data agrees with itself."City Chicago with ZIP 10001, a New York code.

"Granted", in the timeliness line, means guaranteed: up-to-date records must also refer to the same moment, or comparing them makes no sense — the Monday and Friday columns above.

The next slide, "Problems …" (p. 1070), takes the definition apart in four words:

"Data quality means accuracy." Accuracy is one dimension of five. A table in which every value is correct can still be incomplete, stale, inconsistent — or full of duplicates, like the two rows of the hook.

Data quality, conventionally, is accuracy, completeness, uniqueness, timeliness and consistency — a definition that is unmeasurable, context independent, incomplete and vague.

When data is wrong: three bad reactions and a vicious cycle

The first part of the deck, "When Data Is Wrong", opens with three Dilbert strips (pp. 1073–1075), one per wrong reaction to bad data. In each, a manager holds data that nobody trusts.

The three strips, their lines quoted from the panels (the slides print them in capitals; the third title is spelled "practioner" on the slide).
Slide titleWhat is saidWhat goes wrong
"The skeptic approach" (p. 1073)The new performance test turns out to be flawed. Dilbert: "Do I have permission to fake the test data?" The boss: "I didn't even know data can be real."If no data is ever trusted, faking it seems no worse than measuring it. And the defect sits upstream: the process that produces the data is broken.
"The pragmatic approach" (p. 1074)"All of our data is grossly inaccurate… but I need data in order to manage." Then: "If I concentrate hard enough I can forget that the data is bad, then I can use it."Bad data used as if it were good. Knowing that data is bad helps nobody without knowing how it is bad.
"The (pseudo) practioner approach" (p. 1075)Two databases to size the market, and Dilbert says both are wrong. The boss: "Can you average them?" Dilbert: "Sure. I can multiply them too."An operation without a model of the errors: the average means as little as the product.

The third strip is the subtle one. Averaging cancels only random errors that point in different directions; two sources that are wrong in the same way stay wrong on average — the bias of the previous section. Combining sources needs a model of their errors, which source is right about what and by which rule, and the cleansing steps below are that model.

Then the deck states the goal: "Goal: Better Faster Cheaper!" (p. 1076). A bar chart in millions of US dollars per year (no legend, illustrative values) leads, through an arrow labelled "Insights", to a "Better Marketing Campaign" and from there to "$$$". Good data feeds a chain that ends in money. The next slide runs the same chain on bad data and closes it into a ring, "The Vicious Cycle of Bad Data" (p. 1077):

Bad Data → Incorrect Analysis → Invalid Insights → Wrong Decisions → Poor Outcomes → Bad Data

Each arrow is a consequence. An analysis of bad data is incorrect however good the method; insights drawn from it are invalid; decisions taken on them are wrong; the outcomes are poor. Beside the ring a chart of "Revenue(million)" falls from 8 to 4 to 2 to 1 between 2013 and 2016 — values read off the chart, an illustration rather than a real company — under the line "Data Quality is an issue…".

Why a ring and not a chain? The slide draws the closing arrow but does not explain it. A reading of ours, in two parts: outcomes are recorded and become the data of the next round — a campaign aimed at the wrong customers produces response data about the wrong customers. And poor outcomes cost trust, budget and attention — the care that would fix the data. So a better analysis cannot break the ring: the only lever is the data. The widget lets you pull it.

The vicious cycle: how much effort breaks it?

The ring is the slide's (p. 1077); the numbers come from a toy model of ours, explained under the widget. One step moves to the next node, five steps make a turn, and Run the cycle plays eight turns. In every turn the wrong decisions spoil some of the good records, while the effort you set fixes bad ones — with a budget that shrinks when the outcomes are poor. The plot keeps the share of bad data at the start of every turn.

  1. Keep the effort at 5 % and the start at 25 % bad data. Predict: after eight turns, more or less bad data than now? Then press Run the cycle. The one thing to watch is whether each turn starts from better or worse data than the one before.
    What you should see

    More, and faster and faster: 25 → 30.6 → 37.8 → 46.4 … → 89.7 % after eight turns, and the readout says the cycle feeds itself. Each turn starts from worse data than the last, because the wrong decisions spoil more records than the effort fixes. That is what makes it a cycle and not a chain.

  2. Find the smallest effort that stops the climb from 25 %. Guess a number first, then try it.
    What you should see

    13 %. At 12 % the share still creeps up (25 → 35.8 % in eight turns); at 13 % it turns down (25 → 12.1 %), and the fall speeds up with every turn, because less bad data means better outcomes and a bigger budget for fixing. The readout "break-even effort now" shows 12.5 %: in this model it is always half the share of bad data.

  3. Keep 13 % and set the start to 50 %. Does the effort that broke the cycle still break it?
    What you should see

    No: the share climbs from 50 to 94 %. The break-even effort is now 25 %. With more bad data each turn spoils more records, and the poorer outcomes leave less budget to fix them: the later you start, the more it costs to break the cycle. At 26 % the curve bends down again.

The toy model behind the widget, in one formula
\[ \begin{aligned} q_{t+1} = q_t &+ 0.5\,q_t\,(1 - q_t) \\ &- \min\bigl(q_t,\; e\,(1 - q_t)\bigr) \end{aligned} \]
\(q_t\)
share of bad records at the start of turn \(t\)
\(0.5\,q_t(1 - q_t)\)
good records spoiled by the wrong decisions of the turn
\(e\)
the effort: the share of records the team could fix with a full budget
\(e\,(1 - q_t)\)
what it fixes when the budget follows the outcomes, \(1 - q_t\)

While the team cannot fix every bad record in one turn, the share changes by \((1 - q_t)(0.5\,q_t - e)\): it grows when \(e \lt 0.5\,q_t\) and falls when \(e \gt 0.5\,q_t\). The break-even effort is half the share of bad data, so the worse the data, the more effort it takes. The factor 0.5 and the shape of the formula are ours; the slide only draws the ring.

The section ends on two authorities (p. 1078). A "Gartner Report" forecast: "By 2017, 33% of the largest global companies will experience an information crisis due to their inability to adequately value, govern and trust their enterprise information." The crisis is not a lack of data but a lack of trust — and 2017 is past, so read the sentence as a prediction, not a measurement. Then a quotation: "If you torture the data long enough, it will confess to anything", signed "Darrell Huff".

The warning stands whoever said it. Wrangling changes data, and a change made to reach a wanted answer is torture. Every step that follows is justified by something other than the answer: a business rule, a reference, a second source.

Bad data feeds itself — Bad Data, Incorrect Analysis, Invalid Insights, Wrong Decisions, Poor Outcomes, more Bad Data — and only work on the data breaks the ring.

Making a wrong right: what data wrangling is

The second part of the deck, "Making a Wrong Right", opens with a definition (p. 1080):

Data wrangling — "The process of transforming 'raw' data into data that can be analyzed to generate valid actionable insights".

Three parts. The input is "raw" — in quotes on the slide: data as it comes from the source, whatever its shape. The output can be analysed. And the purpose is insights that are valid — not the "Invalid Insights" of the ring — and actionable: they can become decisions.

Above the definition the slide draws the data-science pipeline as five chevrons (Fig. 1, left): Data Acquisition, Data Preparation, Data Analysis, Data Visualization, Results Interpretation. It marks none of them, but wrangling is the second: the next slide lists "Data Preparation" among its names (p. 1081), and the course notes say "The step after Data Acquisition and before Analysis in the data management flow is Data Wrangling" (§5.2.1). So it comes after acquiring the data — from web APIs or by scraping, for instance (lesson 34) — and before analysing it. Under the chevrons: "Data scientists spend more time on preparing data than on analyzing it". The slide gives no number; the same section of the notes does: "in average 80% of the time of a data scientist is spent cleaning data".

That next slide gives eight names for the same activity (p. 1081): Data Preprocessing, Data Preparation, Data Cleansing, Data Scrubbing, Data Munging, Data Transformation, "Data Fold, Spindle, Mutilate…" — a joke on the warning once printed on punched cards, "do not fold, spindle or mutilate" — and "(good old) ETL". The last name carries the message: wrangling is not new.

ETL, Extract-Transform-Load, gets a slide of its own (p. 1082): an "Information architecture pattern for datawarehouse solutions" and "Batch oriented data integration and delivery". Data is extracted from the operational sources, transformed into the warehouse's schema — and cleaned on the way — then loaded, in periodic batches rather than record by record as in a streaming pipeline. Lesson 4 has the course's longer definition, "Extract Transform Load (in the Big Data era)" (p. 175), and lesson 23 the warehouse it feeds. The a.k.a. slide's message is that wrangling is "(good old) ETL" under a newer name — in our reading, above all its T, where data is reshaped and cleaned.

"Cleansing, munging and wrangling mean the same." In conversation, yes — that is the slide's point. In an answer, use the narrower senses the deck gives elsewhere: data cleansing has its own definition, detecting and correcting (or removing) corrupt or inaccurate records (p. 1084, next section), data munging means "potentially lossy transformations" (p. 1102, lesson 36), and Transform is one wrangling step of six.

Six steps, in a loop

"Data Wrangling Steps" (p. 1083) draws six boxes — Obtain, Understand, Explore, Transform, Augment, Shape — and writes beside them "Iterative process". The slide prints only the names; in one line each, our glosses:

pipeline (p. 1080) wrangling steps (p. 1083) Data Acquisition Data Preparation Data Analysis Data Visualization Results Interpretation Obtain Understand Explore Transform Augment Shape Visualize Iterative process
Fig. 1. Left: the data-science pipeline, the five chevrons of p. 1080 set top to bottom; data wrangling is the highlighted Data Preparation stage. Right: that stage opened into the six boxes of p. 1083. The slide draws no loop: the arrow back through Visualize, a word from the list beside the boxes, is our drawing of "Iterative process" — look at the shaped data, find new problems, go back to Understand.

Iterative means that loop: no data set is clean after one pass. The architecture deck has a shorter version of the same picture: wrangling "includes understanding, cleansing, augmenting and shaping data", four boxes instead of six (p. 160, lesson 3).

"The last step is Visualize" — or is it Shape? The slide answers both ways: the diagram starts with Obtain and ends with Shape, the list beside it starts with Understand and ends with Visualize. Read the boxes as the process and the list as the loop that repeats; in an answer, name the six boxes and add that the result is visualized and the process iterated.

Data wrangling, a.k.a. "(good old) ETL", is the Data Preparation stage: an iterative process of obtaining, understanding, exploring, transforming, augmenting and shaping raw data until it can generate valid actionable insights.

Data cleansing, and why data is dirty

Inside wrangling the deck singles out one activity (p. 1084):

Data cleansing — "Data cleansing or data scrubbing is the act of detecting and correcting (or removing) corrupt or inaccurate records from a data set. The term refers to identifying incomplete, incorrect, inaccurate, partial or irrelevant parts of the data and then replacing, modifying, filling in or deleting this dirty data."

The first sentence works on whole records: detect, then correct — or, as the bracket allows, remove. The second works on parts of records: five kinds of defect (incomplete, incorrect, inaccurate, partial, irrelevant) and four remedies (replacing, modifying, filling in, deleting). Deleting is the last resort; the course notes add "(when it's just too noisy to be fixed)", and lesson 36 counts what dropping records costs.

Where does the dirt come from? "Why is Data 'Dirty'?" (p. 1085) lists eleven causes. The slide prints only the names; the examples are ours.

The eleven causes of p. 1085, in the slide's order, each with an example of ours.
CauseAn example
Dummy ValuesZIP 99999, typed only to get past a mandatory field
Absence of Dataan empty phone field
Multipurpose Fieldsa "reference" column that holds an invoice number in some rows and a customer name in others
Cryptic Datathe title "SLS MGR"; a status column with the values X3 and Q
Contradicting Datacity Chicago with a New York ZIP code; two birth dates for one customer
Shared Field Usagea "notes" field that logistics uses for delivery hints and finance for credit limits
Inappropriate Use of Fieldsa phone number typed into the second address line
Violation of Business Rulesan order dated before the customer registered; a discount of 150 %
Reused Primary Keyscustomer 1047 was a bakery, then the id went to a dentist — and the bakery's old orders now point at the dentist
Non-Unique Identifierstwo branches give the same customer number to two different people
Data Integration Problemstwo sources with different formats, codes and keys for the same person — the hook

Read the list by kind. Some causes are bad values: dummy, absent, cryptic, contradicting. Some misuse the structure: multipurpose, shared and inappropriately used fields. Some break the organisation's own rules and keys: business rules, reused keys, non-unique identifiers. The last appears only when sources are merged. Dirty data is not just typos: it is a by-product of how data is entered, designed and combined — which is why it keeps coming back.

Data cleansing detects and corrects — or removes — corrupt or inaccurate records; data gets dirty through eleven causes, from dummy values to data integration problems.

Cleansing in practice: one record, five steps

"Data Cleansing in Practice" (p. 1086) is a list of five activities in a fixed order: Parsing, Correcting, Standardizing, Matching, Consolidating. Each has a definition slide and an example slide, and the examples follow one record — Beth Parker of the hook — from the label to the end. Step through them; the end of each step says why it stands where it stands.

  1. Parsing — "Parsing locates and identifies individual data elements in the source files and then isolates these data elements in the target files." (p. 1087). The five lines of the label become ten named fields (p. 1088): First Name Beth, Middle Name Christine, Last Name Parker, Title SLS MGR, Firm Regional Port Authority, Location Federal Building, Number 12800, Street Lake Calumet, City Hedgewisch, State IL. No value changes: "Hedgewisch" and "SLS MGR" stay. Why first: every later step works on fields, and a field must exist before it can be fixed.

  2. Correcting — "Corrects parsed individual data components using sophisticated data algorithms and secondary data sources." (p. 1089). Looked up in a postal reference, the address changes (p. 1090): Street becomes South Butler Drive, City becomes Chicago, and two fields are added, Zip 60633 and Zip+Four 2398. Why second: the reference is searched by number, street, city and state, so these must already be separate; and a secondary source is needed because a record cannot certify its own accuracy — the "unmeasurable" of p. 1070.

  3. Standardizing — "Standardizing applies conversion routines to transform data into its preferred (and consistent) format using both standard and custom business rules, as well as coherent measurement units, …" (p. 1091). Four changes (p. 1092): a Pre-name Ms. is added; the "1st Name Match Standards" Elizabeth, Bethany, Bethel list the names Beth may stand for; SLS MGR becomes Sales Mgr.; South Butler Drive becomes S. Butler Dr. "Preferred" means the agreed convention — here the short postal form, not the longest one — and coherent units are the same idea for numbers: every weight in kilograms, every price in one currency. Why third: values in different formats never compare equal.

  4. Matching — "Searching and matching records within and across the parsed, corrected and standardized data based on predefined business rules to eliminate duplications." (p. 1093). A second source holds Ms. Elizabeth Christine Parker-Lewis at 12800 S. Butler Dr., Suite 2, with a phone and a fax (p. 1095). Field by field: Elizabeth is among Beth's match standards, Parker is part of Parker-Lewis, the streets differ only by the suite, and firm, city and ZIP are identical — under a matching rule (the match patterns below), a duplicate. "Within and across" means inside one file and between files. Why fourth: the definition names its own input, "parsed, corrected and standardized data".

  5. Consolidating — "Analyzing and identifying relationships between matched records and consolidating/merging them into ONE representation." (p. 1096). The result (p. 1097): Ms. Beth (Elizabeth) Christine Parker-Lewis, Sales Mgr., Regional Port Authority, Federal Building, 12800 S. Butler Dr., Suite 2, Chicago, IL 60633-2398, phone 708-555-1234, fax 708-555-5678. Why last: only records that were matched can be merged.

The slides print in red the values a step changed or added (pp. 1090, 1092) and, on the matching slide, the values on which the two sources differ (p. 1095). Fig. 2 sets the two sources next to the final record and shows where every value of the result came from.

labels.txt — file #1 (p. 1088) Beth Christine Parker, SLS MGR Regional Port Authority Federal Building 12800 Lake Calumet Hedgewisch, IL crm.csv — file #2 (p. 1095) Ms. Elizabeth Christine Parker-Lewis Regional Port Authority Federal Building 12800 S. Butler Dr., Suite 2 Chicago, IL 60633-2398 708-555-1234 · 708-555-5678

Before: two files, two people?

Consolidated Data (p. 1097) Name: Ms. Beth (Elizabeth) Christine Parker-Lewis Title: Sales Mgr. Firm: Regional Port Authority Location: Federal Building Address: 12800 S. Butler Dr., Suite 2 Chicago, IL 60633-2398 Phone: 708-555-1234 Fax: 708-555-5678 postal reference (correcting) business rules (standardizing) file #2 (consolidating) unchanged from the label, file #1

After: one record, every value accounted for

Fig. 2. The record of the hook before and after the five steps. Left: the two sources with the values the slides print (the file names and the layout of file #2 are ours); the highlighter marks the four values on which they disagree. Right: the consolidated record of p. 1097, each value marked by where it comes from — ochre, solid outline: the postal reference used by correcting (the street name was then shortened by the rules); violet, dashed: the business rules of standardizing; magenta, dotted: file #2, brought in by consolidating; no mark: unchanged from the label.

Match patterns: a duplicate is a rule, not a feeling

How does a matcher decide? "Match Patterns" (p. 1094) is a table of rules for business records: six compared fields, a grade for each, a pattern code and an identifier.

"Match Patterns" (p. 1094), cell by cell as printed. The highlighted row is the subject of the red pen below.
Business
Name
StreetBranch
Type
Customer
#/Tax ID
CityVendor
Code
PatternPattern
I.D.
ExactExactExactExactExactExactAAAAAAP110
ExactVCloseExactVCloseExactBlanksABAAA-P115
ExactVCloseExactBlanksExactExactABA-AAP120
ExactVCloseCloseCloseExactExactABCCAAS300
VCloseVCloseExactCloseExactExactBBACAAS310

Each row is one rule. The slide does not define the grades; read them as: Exact — identical after standardizing; VClose — very close, apart by an abbreviation, a nickname or a suite number; Close — similar but less so, like Parker and Parker-Lewis; Blanks — empty in at least one record, so the field is no evidence either way, which is not the same as a mismatch. The pattern spells the row with one character per field, in column order: A for Exact, B for VClose, C for Close, "-" for Blanks. The slide does not print this key; its rows force it.

The identifiers come in two families, P110–P120 and S300–S310, which the slide leaves unexplained. A reasonable reading, ours: P rules pass a pair automatically, S rules flag it as suspect for a person to decide — the S rows are the ones where an identifying field, Branch Type or Customer #/Tax ID, drops to Close. Why grade field by field instead of one overall similarity? Fields differ in weight — an exact tax ID is nearly proof, an exact city almost nothing — and a named rule can be explained, audited and changed by the business.

"Matching finds the duplicate; consolidating deletes it." The course notes say so — "If after the pattern matching two pieces of data appear to be referring to the same record, one of them is discarded" (§5.2.2) — but the slides show the opposite. The consolidated record of p. 1097 keeps Beth's title from file #1 and the suite, phone and fax of file #2; deleting either record would have lost something. The slides win: consolidating merges.

The cleansing conveyor: six contacts, five steps

Six contact records from two files enter the five steps of p. 1086. Four are free-text labels of labels.txt — L1 is the label of p. 1088 — and two are rows of a contact list, crm.csv — C1 is "Data Source #2" of p. 1095. The other four records, the postal reference, the tables of names and titles and the matching rule are ours. Next moves the conveyor one step; values changed or added at that step wear the highlighter (the slides print them in red). The first select leaves a step out, the second records your prediction.

  1. Before pressing Next, set your prediction: how many of the six records will leave the conveyor? Then step to Consolidating. The one thing to watch is the step at which the count changes.
    What you should see

    Four. The count stays at 6 through parsing, correcting, standardizing and even matching, and drops only at consolidating: L1 and C1 (Beth Christine Parker and Elizabeth Christine Parker-Lewis) become one record, and so do L2 and L3 (Thomas and Tom Okafor), a duplicate inside the same file. The two Ana Ruiz stay two. The first three steps change no count — they make the records comparable.

  2. Choose "skip standardizing" and predict the count before you step to the end.
    What you should see

    Six: no pair merges. Without standardizing there are no 1st Name Match Standards, so Beth and Elizabeth, Thomas and Tom are just different strings; the patterns read ×CABAA and ×AAAAA. Matching compares values, and values in different formats never match — that is why standardizing comes before matching.

  3. Choose "skip correcting". One duplicate is still found and one is not: predict which, then check at Matching.
    What you should see

    L2 and L3 still merge (BAAAA-): both labels carry the same wrong address, 12800 Lake Calumet, Hedgewisch, so they agree with each other — and the merged record keeps that wrong address. L1 and C1 do not (BCA××-): file #2 knows the building as S. Butler Dr., Chicago. Only the secondary source makes two sources describe the address the same way. Five records leave.

  4. Back to all five steps. At Matching, L4 and C2 share name, building and city: why no merge? And at Consolidating, what does L1 + C1 keep from each file?
    What you should see

    Their firms differ (AA×BAA): two people called Ana Ruiz, or one who changed employer. The rule sends the pair to a person for review instead of guessing. L1 + C1 keeps the title Sales Mgr. from L1, the suite, phone and fax from C1, and both first names — the record of p. 1097. Nothing is thrown away.

Back to the hook. The two rows were one person, but no comparison of the raw rows could show it: first name, surname, street and city all disagreed. Correcting gave the label the address the contact list already had, standardizing made Beth comparable to Elizabeth, and only then could a rule declare the match. The merged record keeps a title only the label knew and a phone only the contact list knew. Nothing was guessed, and nothing was thrown away.

Parse, correct, standardize, match, consolidate: each step makes the next one possible, and the number of records changes only at the last.

Understanding data: a structure nobody wrote down

The four slides that close this part of the deck are titled "Understanding Data" (pp. 1098–1101) — the Understand step of Fig. 1. Each shows data whose structure is not written in it and has to be recovered.

A PDF invoice

To a person a PDF invoice looks structured; to a program it is a drawing of text. The slide shows a "Tax Invoice" of "Musculinity @Last, Inc" and, below it, the flat table extracted from it (p. 1098):

The extracted table of p. 1098, values as printed, turned on its side: each of the slide's two rows is a column here. Only the four highlighted fields differ between the rows; the other nine repeat the invoice.
ColumnRow 1Row 2
CompanyMusculinity @Last, IncMusculinity @Last, Inc
Address123 Top Secret lane|BestLands, TE|84950123 Top Secret lane|BestLands, TE|84950
Bill ToJustin BeefUpNowJustin BeefUpNow
Customer Address1234 Healthy Street|Irving, TX, 75038|USA1234 Healthy Street|Irving, TX, 75038|USA
Invoice11
Date5/6/20165/6/2016
Subtotal139.78139.78
Discount6.996.99
Total132.79132.79
DescriptionNaturally Extracted Magic Muscle Builder PowderPre Workout Super Shake
Quantity42
Unit29.959.99
Amount119.819.98

The numbers pass a check: 4 × 29.95 = 119.80 and 2 × 9.99 = 19.98, together 139.78; 5 % of that is 6.99, and 139.78 − 6.99 = 132.79. The structure does not. The table has one row per line item, so every invoice field is repeated: sum the Total column and you get 265.58, twice the bill. The extraction left parsing work behind — the invoice number 000001 became 1, $119.80 became 119.8, and each address is still packed into one cell with | as separator. And 5/6/2016 is 6 May or 5 June depending on the convention: a job for standardizing. Extraction is where wrangling starts, not where it ends.

Free text in an image

"Python + Textract +Tesseract" (p. 1099): an image holds three typed lines and, under them, "data Wrangling" written by hand. The slide runs this — the call is one line on the slide, split here:

# OCR of the image: returns the text found in it
>>> text = textract.process(
...     '/Users/akuntamu/Downloads/Drawing3.png',
...     method='tesseract-ocr')
>>> text
'     \n   \n\nhow is it going?\nThis is pretty\ninteresting\n\n'

textract is a Python library that extracts text from many kinds of file; for an image it calls Tesseract, an engine for optical character recognition (OCR), which the slide names in the method argument. The typed lines come back with their line breaks. The handwriting is simply not there — and nothing in the output says that a line was lost. That is completeness, the dimension p. 1070 calls unmeasurable, in miniature.

A sentence, and a secret message

The third slide sets a sentence labelled UNSTRUCTURED — "Looks like my V8 Chevy is running low on fuel. Didn't I fill up just the day before?" — above a row labelled STRUCTURED (p. 1100). Ask of each cell where it came from:

The structured row of p. 1100, cell by cell; the third column is our reading.
FieldValueWhere the value comes from
OwnerAKcontext: who is speaking — the sentence only says "my"
VehicleChevyquoted from the sentence
TypeGasinferred: a V8 Chevy runs on gasoline, but no word says so
Fuel Level5%measured: the fuel gauge drawn beside the sentence, not the word "low"
EngineV8quoted from the sentence
Last Fill05/04/16resolved: "the day before" turned into a date, which needs the date of the remark — not on the slide

Two cells are quoted, one is measured, one is resolved against a date the sentence does not contain, one is inferred and one comes from knowing who speaks. Understanding mixes all of these, and each cell is only as reliable as its evidence.

The last slide is a puzzle (p. 1101): "Decode the following secret message:" DALDFWSFOEWRBOSDCALAXORDJFKMCO.

Check yourself: decode it before you open this

Ten airport codes of three letters each, which the slide splits as DAL DFW SFO EWR BOS / DCA LAX ORD JFK MCO: Dallas Love Field, Dallas/Fort Worth, San Francisco, Newark, Boston, Washington National, Los Angeles, Chicago O'Hare, New York JFK and Orlando. Two pieces of knowledge from outside the string make it readable: a layout (tokens of a fixed width of three, no separator) and a dictionary (the IATA airport codes). Without them the same 30 letters are "Cryptic Data" (p. 1085); cut them every 2 or every 4 letters, and the result is nonsense.

All four slides make one point. The structure is not in the bytes: it is knowledge you bring — a layout, a dictionary, a date, a sensor. That is why "metadata" is on the list of what the conventional definition forgot (p. 1070), and why Understand comes right after Obtain.

Understanding data means recovering a structure that is not written in the data — and what extraction produces is dirty data in its turn, to be parsed, standardized and shaped.

Exam-style questions

Theory questions in the form of the written exam — short open answers, multiple-choice and true/false questions; whether wrong answers carry a penalty is announced just before the exam. Data wrangling is not among the topics of the practical part, so all seven are theory questions.

Give the conventional definition of data quality presented in the course, with its five dimensions, and explain the four problems the course attributes to it.

Show model answer

The conventional definition describes data quality along five dimensions: accuracy (the data was recorded correctly), completeness (all relevant data was recorded), uniqueness (entities are recorded once), timeliness (the data is kept up to date, with time consistency guaranteed) and consistency (the data agrees with itself). The course lists four problems with this definition. It is unmeasurable: accuracy and completeness are extremely difficult, perhaps impossible, to measure, because the true values and the missing records are not in the data. It is context independent: it does not account for what is important for the use of the data — for example, aggregates can tolerate a lot of inaccuracy. It is incomplete: it says nothing about interpretability, accessibility, metadata or analysis. And it is vague: it gives no guidance towards practical improvements of the data.

The five names and the four problems are the skeleton; each needs its meaning, not just the word. One clause on why accuracy is unmeasurable — no reference inside the data — shows that the list is understood and not only recalled.

"If you are computing aggregates, you can tolerate a lot of inaccuracy." Which problem of the conventional definition of data quality does the course illustrate with this example?

  • Unmeasurable That problem says accuracy and completeness are hard to measure; the example is about how much inaccuracy matters for a given use.
  • Context independent The definition makes no account of what is important: the same inaccuracy is harmless in an aggregate and serious in a single record.
  • Incomplete That problem is about dimensions the definition leaves out: interpretability, accessibility, metadata, analysis.
  • Vague That problem is the lack of guidance towards practical improvements of the data.
Show model answer

Context independent. The conventional definition does not account for what is important for the use of the data: random errors in single records largely cancel out in sums and averages, so an aggregate tolerates an inaccuracy that a single record, such as a customer's bill, cannot.

"Unmeasurable" is the tempting wrong option, because both lines of the slide mention accuracy. The key words are "what is important": quality depends on the use.

Describe the vicious cycle of bad data. Why is it a cycle rather than a chain, and where can it be broken?

Show model answer

Bad data leads to incorrect analysis, incorrect analysis to invalid insights, invalid insights to wrong decisions, and wrong decisions to poor outcomes; poor outcomes in turn produce more bad data. It closes into a cycle because the outcomes of wrong decisions are recorded and become the data of the next analysis, and because poor outcomes reduce the budget and the attention available to fix the data. A better analysis method cannot break it, since the analysis is incorrect because of its input. The cycle is broken at the data itself, by investing in its quality through data wrangling and cleansing, which turns it into the chain of the course's goal: good data, insights, better decisions, better outcomes.

The five stages in the slide's order are the minimum. The slide (p. 1077) draws the closing arrow without explaining it, so the reason the loop closes is the part that shows understanding; the last sentence connects it to "Making a Wrong Right".

What is data wrangling? Place it in the data science pipeline, list its steps, and explain how it relates to ETL.

Show model answer

Data wrangling is the process of transforming raw data into data that can be analyzed to generate valid actionable insights. In the data science pipeline — data acquisition, data preparation, data analysis, data visualization, results interpretation — it is the data preparation stage, after acquisition and before analysis, and it usually takes more of a data scientist's time than the analysis itself. It is an iterative process with the steps obtain, understand, explore, transform, augment and shape; the result is visualized and checked, and the process goes back to understanding when new problems appear. ETL (Extract-Transform-Load) is the batch-oriented information architecture pattern used to feed data warehouses: data is extracted from the sources, transformed into the target schema and loaded. The course lists "(good old) ETL" among the other names of data wrangling: wrangling is essentially the transform step of ETL under a newer name, not a new technique.

Give the definition close to the slide's words: raw data in, analysable data out, valid actionable insights as the purpose. Because the slide's diagram and list disagree on the last step, naming the six boxes and adding that the result is visualized covers both readings.

Which of the following does the course list among the reasons why data is "dirty"? Select all that apply.

  • Dummy values On the list: placeholders typed to get past a mandatory field, such as ZIP 99999.
  • Denormalised tables Not on the list. Redundant copies can end up contradicting each other through update anomalies (lesson 9), but the slide names the symptom, "Contradicting Data", not this design choice.
  • Reused primary keys On the list: an identifier given to a new entity, so old records point at the wrong one.
  • Shared field usage On the list: one field used by two departments for different purposes.
  • Replica lag in a distributed database Not on the list: a consistency issue of distributed systems (lesson 5), not of how data is entered or combined.
  • Non-unique identifiers On the list: a "key" that does not identify, such as the same customer number given to two people.
Show model answer

Dummy values, reused primary keys, shared field usage and non-unique identifiers. The full list of the course: dummy values, absence of data, multipurpose fields, cryptic data, contradicting data, shared field usage, inappropriate use of fields, violation of business rules, reused primary keys, non-unique identifiers and data integration problems.

Wrong answers may be penalised, so ticking a plausible-sounding impostor can cost you. Learning the eleven causes by kind — values, misuse of structure, rules and keys, integration — makes the impostors easy to spot.

Name, in order, the five activities of data cleansing in practice and explain what each does, using the example of the course where it helps. Why can matching only be done after the first three?

Show model answer

Parsing locates and identifies the individual data elements of the source and isolates them in target fields: the label "Beth Christine Parker, SLS MGR, …, 12800 Lake Calumet, Hedgewisch, IL" becomes first name, last name, title, number, street, city and so on, with the values unchanged. Correcting fixes the parsed components with sophisticated algorithms and secondary data sources: a postal reference turns Lake Calumet, Hedgewisch into South Butler Drive, Chicago and adds the ZIP code 60633-2398. Standardizing converts the values into their preferred and consistent format with standard and custom business rules and coherent measurement units: "SLS MGR" becomes "Sales Mgr.", the street "S. Butler Dr.", and the pre-name "Ms." and the first-name match standards (Elizabeth, Bethany, Bethel) are added. Matching searches records within and across sources for duplicates by predefined business rules, grading each field as exact, very close, close or blank: Beth Parker matches Elizabeth Parker-Lewis of a second source. Consolidating identifies the relationships between the matched records and merges them into one representation that keeps the best value of every field. Matching compares field values, so it needs the first three steps: without parsing there are no fields, without correcting the two sources spell the same address differently, and without standardizing "Beth" and "Elizabeth" never compare as equal.

The order is half the answer, and the reason for the order is the other half. The example is optional but makes every definition concrete; the values are those of pp. 1088–1097.

True or false: when two records are recognised as duplicates, consolidating keeps the more complete of the two and discards the other.

  • True That would be deletion. The consolidated record of the course takes values from both records.
  • False Consolidating merges the matched records into ONE representation: title from the first source, suite, phone and fax from the second, both first names kept.
Show model answer

False. Consolidating analyses and identifies the relationships between matched records and merges them into one representation. In the course's example the consolidated record takes the title from the first source and the suite number, phone and fax from the second, and keeps both first names: Ms. Beth (Elizabeth) Christine Parker-Lewis.

The course notes (§5.2.2) end with "one of them is discarded"; the slides show the merge, and the slides are the reference.

Check yourself

In the conveyor widget with all five steps on, at which step does the number of records first change?

  • Parsing, because the labels are split into fields Splitting changes the structure of a record, not the number of records: six in, six out.
  • Correcting, because wrong addresses are replaced Values change; records do not.
  • Matching, because duplicates are eliminated Matching finds and marks the duplicates — eliminating them is its purpose — but the merge itself is the next step.
  • Consolidating, because matched records are merged Each group of matched records becomes ONE representation: 6 → 4.

A contact row says city Chicago and ZIP 10001, a New York code. Using only the data itself, what can you say?

  • Accuracy is violated, consistency holds, because each value is well formed Consistency is not about format: "the data agrees with itself", and here two fields disagree.
  • Consistency is violated; which value is inaccurate cannot be told without a reference outside the data The contradiction is visible inside the data; finding the wrong value needs a secondary source — the "unmeasurable" problem.
  • Uniqueness is violated Uniqueness is about one entity recorded twice; this is a single row.
  • Timeliness is violated Perhaps one field was updated and the other was not, but nothing in the row says so. What the data itself shows is the disagreement.

Which changes in Beth Parker's record are made by standardizing (p. 1092)? Select all that apply.

  • SLS MGR becomes Sales Mgr. A standard abbreviation rule turns a cryptic title into the preferred one.
  • Lake Calumet becomes South Butler Drive Correcting (p. 1090): the street comes from the postal reference.
  • The pre-name Ms. is added A business rule of standardizing: it is printed in red on p. 1092, not on p. 1090.
  • Zip 60633 and Zip+Four 2398 are added Correcting (p. 1090): the reference adds them.
  • South Butler Drive becomes S. Butler Dr. The preferred format is the short postal form.
  • Beth becomes Beth (Elizabeth) Consolidating (p. 1097): the merged record keeps both names.

The output box of p. 1092 is titled "Corrected Data" — see the red pen. All four values printed in red on it are standardizations.

Two market studies estimate 120 and 80 units, and both are known to overstate the market. A manager averages them: 100. What is wrong, in the spirit of the third strip?

  • Nothing: averaging two estimates always halves the error It reduces random errors, not an error that both estimates share.
  • The average should be weighted by the size of each database Weights change how the two are mixed; a bias that both share survives any weighting.
  • Averaging cancels random errors, but both estimates overstate the market, so 100 overstates it too A shared bias does not average out — the limit of "aggregates tolerate inaccuracy".
  • The average is right as long as the two studies were made independently Independence helps against noise; it does not remove a bias that both have.

A pair of business records has the pattern ABA-AA under the code of p. 1094. What does it say?

  • Street is VClose and Customer #/Tax ID is blank in at least one record; the other four fields are Exact One character per column, in order: A Exact, B VClose, "-" Blanks. This is rule P120.
  • Street is Close and Customer #/Tax ID differs B is VClose (C would be Close), and "-" means blank — no evidence — not a difference.
  • The fourth field disagrees, so the pair is rejected A blank field is no evidence either way, and the table lists this very pattern as rule P120.
  • Business Name is VClose and Street is Exact The characters follow the column order: the first is Business Name (A, Exact), the second Street (B, VClose).

You load the extracted invoice table of p. 1098 and sum its Total column. What do you get?

  • 132.79, because the extraction keeps one total per invoice It keeps one row per line item, and the invoice total is copied onto each row.
  • 139.78, because the Total column holds the subtotal Total is 132.79 on each row; 139.78 is the Subtotal column.
  • 139.78, because the Total column holds the line amounts The line amounts are in the Amount column: 119.8 and 19.98.
  • 265.58, because the invoice total is repeated on both line-item rows Two kinds of thing in one table — the invoice and its lines — a problem for the Shape step.

In the vicious-cycle widget, 13 % effort breaks the cycle when 25 % of the data is bad, but not when 50 % is. Why, in that model?

  • Because the tipping point does not depend on the effort It does: the share falls whenever the effort is more than half the share of bad data.
  • Because with more bad data each turn spoils more records and the budget for fixing shrinks: break-even is 25 % there Break-even effort = 0.5 × the share of bad data: 12.5 % at 25 %, 25 % at 50 %.
  • Because 13 % is the most effort the model allows The slider goes to 30 %, and 26 % already bends the curve down from 50 %.
  • Because at 50 % the data is beyond repair at any effort At 26 % or more the share falls — slowly at first, then faster.

Key take-aways

What to watch and read