Artificial Intelligence • Data Engineering and Preparation • 18 min read

Data Cleaning and Preprocessing

A machine-learning model can only learn from the examples it receives. Real-world records often contain missing measurements, conflicting labels, duplicate rows, inconsistent units, and values that cannot be interpreted correctly without additional context. Data cleaning and preprocessing are the steps that identify these problems and prepare data for reliable analysis or model development.

These steps are related but not identical. Data cleaning detects and addresses errors, inconsistencies, and quality problems. Data preprocessing is the broader process of converting collected data into a form suitable for a particular task. Cleaning is often part of preprocessing, alongside parsing, transformations, and constructing model inputs.

This article follows Data Types and Data Collection for AI. It focuses on inspecting and correcting raw records; the next articles cover Feature Engineering, Encoding, and Scaling and Data Splitting, Labeling, and Leakage in greater depth.

First intuition: one messy row can change a result

Imagine recording a machine’s temperature three times: 40, 41, and 400 degrees Celsius. The third number could be a sensor fault, a unit error, or a genuine dangerous condition. Deleting it immediately would be a mistake. First compare it with the device’s operating limits, logs, and nearby readings.

Similarly, a blank age might mean “not recorded” rather than zero; two matching rows might be legitimate repeated measurements rather than duplicates. The first step in cleaning is therefore understanding what a valid observation should mean.

Raw valuePossible issueResponsible first action
Empty temperatureMissing measurementCheck source and missingness reason
400 °CPotential outlierVerify unit, sensor range, and event logs
active, ActiveInconsistent categoriesNormalize after confirming equivalent meaning
Two identical rowsPossible duplicateCheck identifiers and timestamps before removal

This article shows how to turn those decisions into documented, repeatable operations rather than a sequence of unexplained edits.

1. Where cleaning fits in the data lifecycle

A typical workflow begins with records from a database, file, sensor, or application. Those records must be understood before being changed.

Data workflow showing raw data flowing through profiling, cleaning, validation, and task-specific preprocessing to a usable dataset
Data preparation is a sequence of explicit, testable decisions, not an automatic “fix everything” operation.

The sequence is useful as a mental model, but real projects revisit earlier steps when validation reveals a new issue. Importantly, model-related preprocessing must respect the training, validation, and test split. Some statistics used in transformations must be learned only from the training portion.

2. Define what a valid record means

A value is not necessarily wrong because it looks unusual. Data quality depends on the meaning of the field and the task.

Suppose a dataset describes industrial machines:

machine_idtemperature_cvibration_mm_soperating_hoursstatus
M0164.22.1180normal
M0291.47.81420fault
M033.4610normal
M033.4610normal
M04920.02.9-10Normal

Several problems are visible: a missing temperature, a repeated record, a suspicious temperature, a negative operating-hours value, and inconsistent capitalization. However, the correct treatment depends on the data source. For instance, repeated measurements from a time-series sensor may be legitimate if their timestamps differ. A temperature of 920.0 may be a unit error or a sensor fault, but it should not be silently changed to 92.0 without evidence.

Common dimensions of data quality

DimensionQuestion to askExample
CompletenessAre required values present?Missing temperature
ValidityDo values follow agreed rules?Negative operating hours
ConsistencyDo representations agree?Normal versus normal
UniquenessAre records duplicated when they should be unique?Repeated event identifier
AccuracyDo values reflect reality?Incorrect sensor reading
TimelinessIs the information recent enough for its purpose?An outdated device status
IntegrityAre relationships and identifiers preserved?Measurement assigned to the wrong machine

A value can be valid according to its data type while still being inaccurate. For example, temperature_c = 920.0 is a valid floating-point number, but may not be a credible measurement in the intended environment.

3. Inspect and profile data before changing it

Data profiling is the systematic examination of a dataset’s structure, value distributions, missingness, and potential anomalies. Start by learning what is present.

For tabular data, useful initial checks include:

  • Number of rows and columns.
  • Column names and inferred data types.
  • Counts of null and non-null values.
  • Unique identifiers and repeated records.
  • Minimum, maximum, median, and other descriptive statistics.
  • Frequencies of categorical values.
  • Unexpected values, formats, and units.

In Pandas:

import pandas as pd

raw = pd.DataFrame({
    "machine_id": ["M01", "M02", "M03", "M03", "M04"],
    "temperature_c": [64.2, 91.4, None, None, 920.0],
    "operating_hours": [180, 1420, 610, 610, -10],
    "status": ["normal", "fault", "normal", "normal", "Normal"],
})

print(raw.shape)
print(raw.dtypes)
print(raw.isna().sum())
print(raw.describe(include="all"))
print(raw["status"].value_counts(dropna=False))

These commands describe the data; they do not prove which records are wrong. Automated checks are most useful when paired with documentation, knowledge of the collection process, and conversations with people who understand the source.

4. Handle missing values deliberately

A missing value represents information that is absent or unavailable. In tabular datasets, it may appear as a null value, empty cell, special string such as unknown, or an impossible placeholder such as -999.

Different placeholder conventions must be identified before they can be treated consistently. A literal zero is not automatically missing: for some variables it is a meaningful measurement.

Why values are missing

Missingness can result from failed sensors, optional fields, inaccessible records, skipped questions, data transmission errors, or deliberate withholding. The reason matters because it can affect how representative the remaining data is.

A useful conceptual distinction is:

  • Missing completely at random (MCAR): Missingness is independent of observed and unobserved data values.
  • Missing at random (MAR): Missingness may depend on observed variables but not on the missing values after accounting for those observations.
  • Missing not at random (MNAR): Missingness still depends on unobserved values, even after considering observed information.

These are statistical assumptions, not labels that can always be determined by inspecting a table. For example, extremely high temperatures might be more likely to cause a sensor to fail. In that case, replacing all missing temperatures with an average could hide precisely the behavior the model needs to detect.

Common treatment strategies

StrategyAppropriate whenMain risk
Remove rowsMissingness is rare and records are not essentialLosing data or introducing bias
Remove a columnThe field is unusable or not requiredDiscarding useful information
Fill with a constantA documented placeholder is meaningfulCreating an artificial pattern
Mean or median imputationA numerical estimate is reasonableReducing observed variation
Most-frequent imputationA categorical value can be approximatedInflating the majority category
Forward fillOrdered observations justify carrying a previous value forwardPropagating stale information
Model-based imputationRelationships support a more complex estimateExtra assumptions and leakage risk

For skewed numerical data, a median may be more robust than a mean. Neither is universally correct. If missingness itself carries useful information, a missingness indicator may be considered as a feature.

Important: For a predictive model, learn imputation statistics from training data and apply the same learned transformation to validation and test data. Computing a median from the entire dataset before splitting can leak information.

5. Detect and address duplicate records

A duplicate record represents the same underlying observation more than once when only one copy should exist. Duplicate detection requires a definition of record identity.

Exact duplicate rows are straightforward to identify:

print(raw.duplicated().sum())
unique_rows = raw.drop_duplicates()

But exact duplicates and repeated legitimate events are different. A customer may place two identical orders. A sensor may report the same reading at different times. Removing rows only because their feature values match can destroy valid observations.

For an event table, a stable event ID is often preferable to matching every column. If a source legitimately sends updated copies of the same event, determine which revision is authoritative using a timestamp or version field.

Duplicate records can also distort model evaluation. If copies of the same example appear in both training and test data, apparent performance may be unrealistically high. Group-aware splitting or entity-level deduplication may be necessary.

6. Correct types, formats, and inconsistent categories

Raw files often represent numbers and dates as text. Other common inconsistencies include extra whitespace, capitalization differences, inconsistent units, and multiple spellings for the same category.

Parse values into the correct types

import pandas as pd

measurements = pd.DataFrame({
    "temperature_c": [" 24.5 ", "27.1", "not recorded"],
    "sample_date": ["2026-10-28", "2026-10-29", "2026-10-30"],
})

measurements["temperature_c"] = pd.to_numeric(
    measurements["temperature_c"].str.strip(),
    errors="coerce",
)
measurements["sample_date"] = pd.to_datetime(
    measurements["sample_date"],
    errors="coerce",
    utc=True,
)

print(measurements)

Here, errors="coerce" converts unparseable values to missing values rather than guessing their meaning. In production, keep a record of which entries failed parsing and investigate whether the failures indicate a systematic problem.

Normalize documented categories

status = pd.Series(["Normal", " normal ", "FAULT", "fault"])
normalized_status = status.str.strip().str.lower()
print(normalized_status.tolist())

Normalization is safe only when the transformed values truly represent the same category. For example, unknown, not applicable, and none may have distinct meanings. Do not merge categories simply because their names look similar.

Make units explicit

Values such as 37 are ambiguous without a unit. Temperatures may be Celsius or Fahrenheit; distances may be meters or feet; currency amounts may refer to different currencies. Prefer explicit column names or metadata such as temperature_c and preserve the original unit in source records.

Unit conversion should use a documented rule, for example:

TC=(TF−32)59T_{\mathrm{C}} = (T_{\mathrm{F}} - 32)\frac{5}{9}

Converting all values does not fix incorrectly labeled units. First establish what was measured.

7. Distinguish outliers from errors

An outlier is an observation that differs substantially from the rest of the data under some chosen criterion. It may indicate a mistake, but it may also be a genuine rare event.

A fraud-detection system, for example, may be specifically interested in unusually large transactions. Removing every unusual example could make the model worse at identifying fraud.

A simple outlier-detection method: IQR

The interquartile range (IQR) is the difference between the third and first quartiles:

IQR=Q3−Q1\mathrm{IQR} = Q_3 - Q_1

A common exploratory rule flags observations below Q1−1.5 IQRQ_1 - 1.5\,\mathrm{IQR} or above Q3+1.5 IQRQ_3 + 1.5\,\mathrm{IQR}. This is a heuristic, not a universal definition of incorrect data.

import pandas as pd

values = pd.Series([10, 11, 12, 12, 13, 14, 15, 100])
q1 = values.quantile(0.25)
q3 = values.quantile(0.75)
iqr = q3 - q1

lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr

suspected_outliers = values[(values < lower) | (values > upper)]
print(suspected_outliers.tolist())

Inspect flagged records before deciding to remove, cap, transform, or retain them. A data-entry mistake may warrant correction from the source; a legitimate rare observation may be crucial to the objective.

8. Validate relationships and business rules

Checking individual fields is not enough. Some errors appear only when values are considered together.

Examples:

  • An order’s delivery time occurs before its purchase time.
  • A machine’s cumulative operating hours decrease between observations without a documented reset.
  • An identifier in one table has no matching entity in a required reference table.
  • A recorded maximum temperature is lower than the recorded minimum temperature.

These are cross-field or cross-record constraints. Define them alongside single-column checks.

import pandas as pd

checks = pd.DataFrame({
    "machine_id": ["M01", "M02", "M03"],
    "operating_hours": [180, -10, 610],
    "min_temp_c": [20, 35, 80],
    "max_temp_c": [75, 90, 60],
})

invalid_hours = checks["operating_hours"] < 0
invalid_range = checks["min_temp_c"] > checks["max_temp_c"]

invalid_records = checks[invalid_hours | invalid_range]
print(invalid_records)

In this example, nonnegative cumulative hours and min_temp_c <= max_temp_c are assumed requirements. A real application should derive such rules from the system’s data contract, not from arbitrary guesses.

9. Build a reproducible preprocessing workflow

Cleaning performed manually in a spreadsheet is difficult to audit and repeat. A reproducible workflow defines the transformations in code, preserves raw inputs, and makes it possible to explain what changed.

The following example cleans a small table using explicit rules. It does not automatically repair implausible temperatures; instead, it flags them for review.

import pandas as pd

raw = pd.DataFrame({
    "event_id": [101, 102, 103, 103, 104],
    "temperature_c": ["64.2", "91.4", "", "", "920.0"],
    "operating_hours": [180, 1420, 610, 610, -10],
    "status": ["normal", "fault", "normal", "normal", "Normal"],
})

clean = raw.copy()
clean["temperature_c"] = pd.to_numeric(
    clean["temperature_c"], errors="coerce"
)
clean["status"] = clean["status"].str.strip().str.lower()

# The source contract defines event_id as unique.
clean = clean.drop_duplicates(subset=["event_id"], keep="first")

# Invalid records are flagged, not silently overwritten.
clean["invalid_hours"] = clean["operating_hours"] < 0
clean["temperature_needs_review"] = ~clean["temperature_c"].between(
    -40, 200
) & clean["temperature_c"].notna()

print(clean)
print("Rows retained:", len(clean))
print("Missing temperatures:", clean["temperature_c"].isna().sum())
print("Invalid hours:", clean["invalid_hours"].sum())
print("Temperatures for review:", clean["temperature_needs_review"].sum())

The interval -40 to 200 degrees Celsius is an illustrative domain rule, not an authoritative limit for every kind of machine. The appropriate boundaries depend on the device and operating conditions.

The next action is not necessarily to delete flagged records. The team may compare them with source logs, repair verified errors, exclude invalid examples with documented justification, or retain unusual but legitimate measurements.

Make transformations testable

Even a simple workflow benefits from explicit checks:

assert clean["event_id"].is_unique
assert clean["status"].dropna().isin(["normal", "fault"]).all()
assert clean["operating_hours"].dtype.kind in "iu"

Tests help detect changes in upstream data contracts. They should be complemented by reports on unexpected categories, parsing failures, dropped rows, and other quality indicators.

10. Prevent leakage when preparing model inputs

Data leakage occurs when information unavailable during legitimate prediction or evaluation influences model development. Cleaning and preprocessing can accidentally introduce leakage even if the chosen model is correct.

Consider predicting future machine faults from measurements recorded at a given time. Information created after that time, such as a repair report confirming the fault, must not enter the model’s input features for that prediction.

Another, subtler mistake is calculating a fill value or normalization parameter using both training and test records. Even without target labels, this allows information from held-out observations to influence the training pipeline.

A safer workflow is:

  1. Define the prediction time, target, eligible input fields, and evaluation method.
  2. Split examples appropriately, using time-aware or group-aware splitting if the problem requires it.
  3. Fit learned transformations, such as an imputer’s median, on the training subset only.
  4. Reuse those fitted transformations without refitting them on validation or test inputs.
  5. Evaluate the complete pipeline on held-out examples.

For example, Scikit-learn can keep an imputer and model together:

import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

X_train = np.array([[20.0], [25.0], [np.nan], [90.0]])
y_train = np.array([0, 0, 0, 1])
X_test = np.array([[np.nan], [88.0]])

pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("model", LogisticRegression()),
])

pipeline.fit(X_train, y_train)
print(pipeline.predict(X_test))

The example demonstrates the fit on training, transform on new data principle, not a meaningful fault-prediction model. The dataset is far too small for credible performance claims. For comprehensive guidance on splitting and labels, see Data Splitting, Labeling, and Leakage.

Not every cleaning step must wait until after a split. Deterministic correction of known schema errors, standardizing clearly equivalent category spellings, or removing invalid records according to a fixed rule can sometimes occur earlier. The essential question is whether the operation uses information that would not be available at the relevant prediction or evaluation stage.

11. Cleaning differs across data modalities

The principles of validity, traceability, and representativeness apply beyond tables, but the operations change with the data type.

ModalityTypical issuesCommon preprocessing
TabularNulls, duplicates, inconsistent types, invalid categoriesParsing, deduplication, validation, imputation
TextEncoding errors, corrupted files, inconsistent markupUnicode handling, extraction, normalization, tokenization
ImagesBroken files, wrong orientation, inconsistent dimensionsDecode checks, orientation correction, resizing
AudioIncorrect sample rate, clipping, background noiseFormat checks, resampling, segmentation
Time seriesMissing timestamps, unequal intervals, duplicate timestampsSorting, alignment, resampling with care

Preprocessing should not erase information important to the task. For instance, aggressively removing punctuation may harm sentiment or language understanding, and filtering audio may remove signals relevant to fault detection.

Time-series preparation requires special caution. Randomly shuffling temporally dependent observations can cause future information to influence training. Resampling and interpolation should respect what would have been known at the prediction time.

12. Document every consequential decision

A cleaning pipeline is part of the scientific and engineering evidence behind a model. Good documentation answers:

  • Which source files or tables were used, and which versions?
  • How were missing values represented and treated?
  • Which records were deleted or corrected, and why?
  • Which constraints were validated?
  • What transformations were fitted, and on which split?
  • How many examples remained after each operation?
  • Which known quality issues could not be resolved?

Keep the original dataset accessible under appropriate security and retention controls. Record code versions and transformation configurations so results can be reproduced. This becomes especially valuable when model behavior changes or a data pipeline breaks in production.

13. Common mistakes to avoid

MistakeWhy it is harmfulBetter approach
Deleting every row with a missing valueMay remove important groups or rare casesInvestigate missingness and compare alternatives
Treating every outlier as an errorCan discard meaningful rare eventsVerify against domain knowledge
Removing all similar-looking rowsMay erase genuine repeated eventsDefine record identity first
Silently replacing invalid valuesHides unresolved source problemsFlag, investigate, and document corrections
Filling missing values before evaluation splittingMay leak held-out informationFit learned preprocessors on training data
Assuming parsed numbers have consistent unitsCreates incorrect relationshipsEnforce unit metadata and conversions
Cleaning once manually and forgetting the stepsMakes results difficult to reproduceImplement versioned, tested transformations
Optimizing solely for row countIgnores accuracy, bias, and validityMeasure quality relative to the task

14. Check your understanding

  1. Why is a numerically unusual value not automatically an error?
  2. How does an exact duplicate differ from a legitimate repeated sensor reading?
  3. When might median imputation be preferable to deleting incomplete rows?
  4. Why should a learned imputation value generally be fitted only on the training set?
  5. What information should be logged when records are removed or repaired?
Show suggested answers
  1. It may represent a genuine rare event; the task and source determine validity.
  2. Identity depends on the event and its metadata, especially identifiers and timestamps.
  3. When dropping records would discard substantial useful information and the median is a reasonable estimate, provided missingness is investigated.
  4. Including held-out examples in the fitted statistic can leak evaluation data into training.
  5. Source version, affected record counts, rule or reason, transformation code, and unresolved issues.

References and further reading

Related articles in

Image preview

Fit