Phase 03 of the Data Science Lifecycle

Data Preparation:
Transforming Raw Data into Model-Ready Foundations

Data preparation is phase 3 of the data science lifecycle: raw data are cleaned, condensed into features and cast into reproducible pipelines. The result is a clean, reproducible dataset as the basis for modelling.

Data preparation

The Art of Data Preparation

Data preparation takes up the largest portion of project work. We automate it with robust processes.

Data preparation is the work between the raw data export and the first model. It consists of three steps, each of which gets its own section on this page: data cleaning, that is, handling missing values, duplicates, outliers and inconsistent formats; feature engineering, that is, building features a model can learn from; and building a data pipeline that makes both repeatable. In German the same work is called Datenaufbereitung. It follows data acquisition in phase 2 and delivers the dataset for exploratory data analysis in phase 4.

How much of the project time this takes depends on the state of the sources. We consider the 60 to 80 percent often quoted in the industry plausible as soon as more than one source is involved; measured across all our projects, we do not have that figure. It becomes plannable once it is known beforehand which defects the data contain.

The starting point is almost never a finished dataset but the data your company already produces: ERP tables, exports from the web shop, machine logs, shift books. We work with these data, preferably in your infrastructure; the data do not have to leave your premises. And preparation sometimes stops a project: when the target variable the model is meant to predict does not appear in the data at all, or when it exists only for a period that does not cover the question. Then we say so after the stocktake, not after months.

Data Cleaning

Systematic handling of missing values, duplicates and inconsistencies.

Feature Creation

Deriving meaningful features based on domain knowledge.

Automation

Reproducible pipelines with error handling and quality checks.

Data cleaning

Data Cleaning: Missing Values, Duplicates, Outliers

Data cleaning is the detection and correction of defects in raw data: missing values, duplicates, outliers and inconsistent formats. It is the first and usually longest part of data preparation and answers four questions: What is missing? What is duplicated? What is implausible? What is correct but written differently from the rest? Which answer is right in each case is decided not by statistics alone but by the purpose of the later model. That is why each of the four points comes with a decision rule, not just a list of methods.

Missing values: delete, impute or encode as a feature

A missing value is rarely a coincidence and often a finding in itself: in the dataset of a delivery platform, 38.78 percent of orders were unrated, the most important statement about the platform's data quality. So before you replace anything, it is worth asking why the value is missing.

Three routes are open. Delete: remove rows or whole columns, defensible for a few affected rows with no relation to the target variable. Impute, that is, replace: with the median, the mean, the last known value or an auxiliary model. In a customer segmentation we replaced missing income values with the median and removed one extreme value; of 2,240 customer records, 2,232 remained. Encode as a feature: the absence itself becomes information, for instance as a column "income unknown". That is the right route when the absence is systematic, because then it tells the model something about the customer.

A special case is placeholders such as "?", "-1" or "9999" that pass as valid values. In the UCI Adult dataset the column "Workclass" appears 100 percent filled; only after the question mark is declared a missing value do 5.6 percent gaps appear.

Decision rule (our rule of thumb, not a standard): if the missing share of a column is below about five percent and no pattern is recognisable, we delete or simply impute. Above that, or as soon as the absence is related to the target variable, it is encoded as a feature and every imputation is documented. With a very high missing share the column usually only works as a yes/no feature. In the Titanic data the cabin is missing for 77.1 percent of passengers, the age for 19.9 percent.

Duplicates and keys

Duplicates rarely arise from typing errors and mostly from technology: an export ran twice, two systems hold the same customer, a join multiplied rows. In the UCI Adult dataset with 32,561 rows we measured 24 duplicate rows, that is 0.074 percent: low, but not zero, and invisible without a check.

The check runs on two levels: identical complete rows are technical duplicates and are deleted. Rows that match only on the declared key columns, say order number plus date, are business duplicates, and the question is which one is right. The second level presupposes that the key is known at all. In process data, duplicate order numbers are among the defects that decide whether a robust model emerges or a pretty, wrong analysis.

Decision rule: technical duplicates are deleted and their share is logged. Business duplicates are never deleted silently but resolved by a rule agreed with the business department: the most recent state wins, or the state from the leading system. The rule goes into the pipeline as code.

Outliers: measurement error or rare event

Statistically an outlier is a value far outside the rest of the distribution; the classic rule after Tukey draws the line at 1.5 times the interquartile range. In our data quality audit across three public datasets, value plausibility was the dimension that most often lit up red, because heavy tails are the rule in real data. The next step is nonetheless always a human one. Is the value a sensor error, a confused unit or a genuine rare event? In the UCI Adult dataset the column fnlwgt shows a heavy tail and is entirely legitimate as a sampling weight.

The outliers we delete are often the cases the business cares about: the machine failure, the bulk order, the payment default. Anyone who removes them before modelling builds a model for the normal case and is surprised in the emergency. That is why we remove only what is demonstrably mismeasured and flag the rest.

Decision rule: an outlier is deleted only if the error can be named: unit, sensor or typing error. Otherwise it stays in the dataset, gets a flag as its own feature, and the modelling chooses methods that are less sensitive to extreme values, such as the median instead of the mean or tree-based models instead of linear ones.

Formats and units: date, decimal separator, time zones

The least spectacular part of data cleaning causes the latest errors. A date stored as text hardly stands out at first and becomes a drama as soon as a time series model sorts by it; in our audit of 25 years of Apple daily prices such a text date was the first finding. Decimal separators work just as quietly: "1.250" is, depending on origin, one thousand two hundred and fifty or one point two five. A chart in one of our own articles showed English decimal points for a while, while the text beside it used the comma.

Units and time zones belong in the same check: changing units in machine data, timestamps in local time next to timestamps in universal time, daylight-saving changes that make an hour appear twice or not at all. Each of these deviations is harmless on its own; in sum they produce a wrong model.

Decision rule: every column gets a declared type, a unit and, for timestamps, a time zone, as code in the pipeline, not in the head of the person handling it. Gaps in time are counted but not filled automatically: in the Apple prices there were 168 gaps, 2.7 percent of the intervals, and all of them were weekends and exchange holidays.

ProblemDetectionMeasureRisk if chosen wrongly
Missing valuesMissing share per column; declare placeholders such as "?", -1, 9999 as missing valuesDelete, impute or encode as a feature, depending on share and patternSystematic absence is lost as information
DuplicatesIdentical rows; identical keys (ID plus date)Delete technical duplicates, resolve business duplicates by rule with the business departmentAggregates are inflated; the wrong state wins
Outliers1.5 times the interquartile range, 5 sigma, domain plausibility limitsDelete only proven measurement errors, flag the rest, choose robust methodsThe rare event is cleaned away
Formats and unitsType check per column; date as text, decimal separators, time zonesDeclare type, unit and time zone; count time gaps, do not fill themSilent errors that only show up in the time series split

Anyone who wants to know before the project how much cleaning lies ahead gets a finding with a risk traffic light from the Data Quality Check. The cleaning itself is expressly not included there; it is the subject of this phase.

Data Quality Check at a fixed price: the stocktake before phase 3
Feature engineering

Feature Engineering: Domain Knowledge Becomes Features

A feature is a column the model learns from. Feature engineering is the work of building features from raw columns that carry a domain meaning. In our experience this work decides the quality of a model more often than the choice of algorithm, and it is the part of data preparation that does not work without your domain knowledge.

What a feature is: two examples

In our model calculation for predictive maintenance, the machine controller delivers vibration, temperature, current draw and error codes every ten minutes. None of these raw values is a good feature on its own. Good features are the rolling 24-hour mean of the vibration, the trend of the current draw and the number of error codes in the last 72 hours: they summarise what an experienced maintenance engineer would keep an eye on anyway.

Predictive maintenance: servicing by condition instead of by calendar

In fashion retail the strongest feature for the next return is the customer's previous return rate, but only if it is calculated exclusively from orders with an earlier date. Built cleanly, in our analysis of 2.33 million order lines it lifted the predictive quality (ROC-AUC) from 0.696 to 0.737. How free-text comments become countable return reasons is shown by the second use case.

Analysing return reasons: free text becomes causes

Typical transformations

  • Aggregation over time windows: sums, means and trends over 24 hours, 7 days or 12 months. What matters is the window edge: the window ends at the prediction time, never after it.
  • Encoding categories: text such as "payment method" or "machine ID" becomes numbers, classically as one-hot encoding with a yes/no column per category. Target encodings for many categories only with caution, because they easily leak information from the target variable.
  • Scaling and normalisation: for methods that measure distances, columns are brought to comparable magnitudes; in the customer segmentation mentioned, a standardisation and a principal component analysis preceded the comparison of five clustering methods. Tree-based methods do not need this step.
  • Selection (feature selection): features that explain nothing or only repeat others are removed; that keeps the model explainable and the pipeline lean.

Data leakage: the biggest trap

Data leakage means that a feature contains information that cannot yet be available at prediction time. The model looks brilliant in the test and fails in operation. Our analysis of around 50,000 sessions of an online shop shows how large the effect can be: with the basket features from the end of the session the model reached an AUC of 0.961, and without them 0.860. A good ten AUC points were not foresight but a rephrasing of the result. What this finding means for model validation is explained in phase 5. The analysis itself is in the research article.

Three rules follow. First, the split between training and test runs along time or along the unit (session, customer, machine), never row by row; otherwise the same session sits on both sides. Second, every feature is checked for when it is known in operation: the maintenance history up to yesterday is allowed, tomorrow's repair report is not. Third, a surprisingly high metric is grounds for suspicion, not success. If a demo is well above what a clean temporal split yields, the difference is very likely the leakage premium.

Why near-perfect conversion models mostly retell the basket
Data pipeline

Data Pipelines: Reproducible, Tested, Versioned

A data pipeline is the processing route that turns raw data into features in the same order and with the same rules on every run. The term ETL (extract, transform, load) describes the same route from the viewpoint of data storage. Which tool executes it is secondary; what matters are reproducibility, tests and versioning, the three properties from the motto of the chart further down.

Why notebook scripts are not enough: a notebook is the right tool to develop a cleaning routine and the wrong one to operate it; after three weeks nobody knows which export was the basis.

Three things are versioned: the code of the transformations; a frozen data state (snapshot) of the raw data against which every result can be recalculated; and the transformation logic as documentation, that is, which rule applies for which reason. The "documentation of all transformations" among the deliverables of this phase is therefore not an afterthought but a by-product of the pipeline.

Every run checks the schema and the value ranges beforehand: it tests whether the input still matches the expected schema (columns, types, units) and whether the value ranges are plausible, that is, no negative quantities, no timestamps from the future, missing shares below the agreed threshold. Such contract tests against a known schema are a different layer from the diagnosis in phase 2; a complete test suite costs between one and four weeks depending on the data model and in return catches every future export that silently changes its format. If a test fires, the run aborts instead of delivering a quietly wrong result.

Phase 6 takes over the same pipeline: the pipeline that produced the training data later produces the inputs for the model in operation. Anyone who builds two separate routes in phase 3, one for the experiment and one for production, gets deviations in phase 6 that nobody can explain.

The same pipeline in operation: phase 6
Data preparation in practice

Data Preparation in the Mittelstand: Three Typical Starting Points

Three starting points come up again and again in mid-sized companies. None of them is an obstacle; each calls for a different first step.

Excel lists in several departments

Sales keeps customers in one spreadsheet, accounting in a second, production in a third. The same company appears three times, spelled three different ways. Preparation starts here with building the key: which column identifies a customer unambiguously? Only then is cleaning worthwhile. Otherwise you clean three versions of the truth instead of one.

ERP export with free-text fields

The export is neatly structured, but the decisive information sits in the remarks field: the cancellation reason, the special terms, the customer's special request. Language processing translates free text into categories that can be counted. The business department defines the categories, not the model; the model only sorts.

Machine data without a common time axis

Machine controller, manufacturing execution system (MES) and ERP log the same order, but with their own clocks and their own cadence. Before any modelling, the sources have to be linked via timestamps, order and machine IDs. Gaps in time series, changing units and duplicate order numbers are the usual findings here.

Process data without a common time axis: what to clarify before preparation

Schematic flow with example values: on the left the raw dataset (38 percent empty fields, 25 percent unclear entries, 18 percent duplicates, 12 percent mixed formats), on the right the feature dataset (42 features, 98 percent quality, 95 percent coverage, 100 percent tests passed). Example values, not a project measurement.

Data science project approach

Our Approach

01

Cleaning & Harmonisation

Systematically addressing data quality issues across different sources.

02

Feature Engineering

Creating features that best support model learning.

03

Pipeline Development

Automated, versioned data processing workflows.

04

Quality Assurance

Integrated check mechanisms for consistently assured data quality.

Data science deliverables

Typical Deliverables

Prepared, model-ready datasets
Automated processing pipelines
Documentation of all transformations
Integrated quality checks
FAQ on data preparation

Frequently Asked Questions about Data Preparation

What is the difference between data preparation and data cleaning?

Data cleaning is one part of data preparation. It removes defects in the raw data: missing values, duplicates, outliers, inconsistent formats. Data preparation additionally comprises feature engineering, that is, building features that make sense for the domain, and building a pipeline that makes both steps repeatable and checkable.

How do you deal with missing values?

First clarify why the value is missing. If it is missing randomly and rarely, the row is deleted or the value replaced by the median or the last known state. If it is missing systematically, the absence is encoded as its own feature. Placeholders such as "?" or 9999 must be declared as missing values beforehand, otherwise the column wrongly counts as complete.

How much time does data preparation take in a data science project?

The largest part of the project work as soon as more than one source is involved. The often quoted 60 to 80 percent match our experience; measured across all projects, we do not have the figure. The share becomes plannable when a stocktake such as the Data Quality Check shows beforehand which defects to expect.

What is feature engineering and why is it more important than the algorithm?

Feature engineering builds features with domain meaning from raw columns, such as the rolling 24-hour mean of a vibration instead of the single value. An algorithm only finds patterns that are in the features; a better feature usually lifts every model, a better algorithm only the one. That is why this work contains the domain knowledge of your company.

What is data leakage and how do you avoid it?

Data leakage is present when a feature contains information that cannot yet be available at prediction time, such as the basket state at the end of the session for a conversion forecast. It can be avoided by a temporal split between training and test, by checking every feature for the time it becomes known and by distrusting metrics that look too good.

Do our data have to be perfect before a model can be built?

No. Models cope with gaps and noise if both are known and documented. Three things have to be right: the target variable must appear in the data, the period must cover the question, and an unambiguous key must connect the sources. If one of them is missing, preparation stops the project, better early than late.

Can data preparation be automated?

The execution yes, the decisions no. Type checks, duplicate search, missing value statistics and schema tests run automatically in the pipeline with every new data state. Whether an outlier is a measurement error or a real event and which rule applies to business duplicates is decided by a person with domain knowledge, and only once.

Let's talk about your project

Every project is unique. Tell us about your challenge.

Book a free initial call