What is Data Cleaning in Machine Learning?

11 minutes read
What is Data Cleaning in Machine Learning?

A model that scores 95% accuracy in testing and then misfires in production usually isn't broken — its training data was. Missing values, duplicate rows, and inconsistent formats teach an algorithm the wrong pattern long before anyone touches the model architecture.

Data cleaning is the process that catches these problems before they reach the model: finding and fixing missing values, outliers, duplicates, and formatting errors so the data going in actually represents the problem being solved. This guide covers the core techniques, a repeatable workflow, and the leakage mistakes that quietly undo the work.

Understanding data cleaning fundamentals

A spreadsheet full of customer records can look complete and still be unusable — ages stored as text in one column and integers in another, country names spelled three different ways, the same purchase logged twice under two order IDs. Data cleaning is the work of finding and correcting these issues: missing entries, duplicate records, outliers, wrong data types, and inconsistent formatting.

None of this is optional groundwork that happens once. Real datasets accumulate errors continuously — from manual entry, merged systems, sensor drift, or schema changes — so cleaning runs every time a new batch of data joins the training set. The output of a cleaning pass is not a polished dataset for its own sake; it's a dataset where every column means what the schema says it means, and where missingness, duplication, and outliers have been deliberately handled rather than silently ignored.

Data cleaning vs data preprocessing vs data wrangling

These three terms get used interchangeably in job postings and loosely in conversation, but they describe different scopes of work, and mixing them up causes teams to skip steps.

Data cleaning is the narrowest: correcting or removing bad values — missing data, duplicates, outliers, typos — without changing the data's structure or units. Data preprocessing is broader. It includes cleaning, plus the transformations that prepare clean data for a specific algorithm: encoding categories as numbers, scaling features to a common range, and engineering new features. Data wrangling (also called data munging) is broader still — it covers reshaping, joining, and restructuring raw data from its original form (nested JSON, multiple source tables, log files) into the flat, tabular structure cleaning and preprocessing assume already exists.

TermScopeTypical task
Data cleaningFix bad valuesImpute a missing age, drop a duplicate row
Data preprocessingClean + transform for modelingOne-hot encode a category, scale a feature
Data wranglingRestructure raw data into usable formFlatten nested JSON, join three source tables

In practice, a single pipeline run usually does all three in sequence: wrangle the raw sources into one table, clean the values inside it, then preprocess for the model that will consume it.

Data Cleaning vs Data Preprocessing vs Data Wrangling

Why data cleaning determines model performance

A team that sees accuracy plateau often starts tuning hyperparameters first — when the ceiling is sitting in the training data, not the model. Andrew Ng's data-centric AI framing makes this the default diagnosis to check before the model: holding the architecture fixed and improving dataset quality is frequently what moves the accuracy number, because a model can only learn patterns that are actually present and correctly represented in its training data [2].

The scale of the underlying work is well documented. A widely cited CrowdFlower survey found data scientists spend about 60% of their time cleaning and organizing data — more than double the time spent on any other single task, including model building — and 57% rated it the least enjoyable part of the job [1]. Combined with data collection, data preparation overall accounts for roughly 80% of a typical project's time [1].

Why Data Cleaning Determines Model Performance

Cleaning doesn't always help, though, and treating it as a universal fix is its own mistake. Over-aggressive outlier removal can strip out the rare cases a fraud or anomaly model exists to catch. Imputing missing values with column averages can flatten variance a model needed to learn from. The right amount of cleaning depends on what the model is meant to detect — not on getting the dataset as "clean" as possible.

 Model Performance

Core data cleaning techniques

Three categories of problems show up in almost every raw dataset: values that are missing, values that are statistically extreme, and records that duplicate or contradict each other. Each has a different fix, and applying the wrong one introduces new bias rather than removing it.

Handling missing values

The right fix depends on why the data is missing, not just how much is missing. The standard taxonomy, which builds on Rubin's 1976 work, splits missingness into three mechanisms: missing completely at random (MCAR), where the gap has nothing to do with any variable; missing at random (MAR), where it correlates with other observed variables; and missing not at random (MNAR), where the missingness itself depends on the unobserved value — a patient skipping a survey question because of the condition the question asks about [3]. Deleting rows is only safe under MCAR with a small affected share; under MAR or MNAR, deletion biases the remaining sample.

Handling Missing Values

Imputation methods range from simple to context-aware. Mean, median, or mode substitution is fast but compresses variance and can distort relationships between columns. K-nearest-neighbors imputation fills a gap using the values of the most similar rows on other features, which preserves more of the original structure at a higher computational cost [4]. Regression imputation predicts the missing value from other columns directly, which works well when those columns are genuinely correlated with the missing one and poorly otherwise.

Handling Missing Values

Detecting and treating outliers

Two thresholds dominate outlier detection in practice. Tukey's rule flags any value beyond 1.5 times the interquartile range (IQR) above the third quartile or below the first as a potential outlier, and beyond 3 times the IQR as a probable one [5]. The z-score method flags values more than 3 standard deviations from the mean, which works well for roughly normal distributions but loses reliability on skewed data.

A flagged value isn't automatically a removal candidate. The first step is always to check whether it's a genuine data-entry error (an age of 999, a negative price) versus a real, rare event the model needs to see — fraud cases and equipment failures are outliers by definition, and removing them removes the signal the model exists to learn. Where the value is legitimate but distorts a sensitive algorithm, capping it at a threshold (winsorizing) or applying a log transform preserves the data point while controlling its influence.

Detecting and Treating Outliers

Removing duplicates and fixing inconsistencies

Exact duplicates — identical rows from a double-submitted form or a re-run import job — are the easy case; pandas' drop_duplicates() removes them in one call once the relevant columns are identified [6]. Near-duplicates are harder: the same customer entered as "Jon Smith" and "Jonathan Smith," or an address with and without an apartment number. Catching these usually requires fuzzy string matching or record-linkage techniques that score similarity rather than checking for exact equality, since a straight equality check misses every formatting variant.

Inconsistency goes beyond duplicate rows into formatting itself: a status column with "Active," "active," and "ACTIVE" as three distinct values, or dates stored as both MM/DD/YYYY and DD-MM-YYYY in the same column. Standardizing casing, units, and date formats before any aggregation or join runs is what prevents a GROUP BY from silently splitting one category into three.

Removing Duplicates and Fixing Inconsistencies

Transforming and standardizing data

A dataset can be fully clean — no missing values, no duplicates, no unresolved outliers — and still be unusable by most algorithms, because clean isn't the same as numeric and scaled. Categorical text and features on wildly different ranges both need a transformation step before training.

Encoding categorical variables

The right encoding depends on whether categories have an order. One-hot encoding creates a separate binary column per category [7] — correct for unordered values like "country" or "payment method," since it doesn't impose a false ranking. Label encoding assigns each category an integer, which is appropriate only when the categories have a genuine order (small/medium/large); applied to unordered data, it teaches the model a ranking that doesn't exist. Ordinal encoding is the deliberate version of label encoding, where the integer order is explicitly chosen to match a known hierarchy rather than assigned arbitrarily.

Encoding Categorical Variables

Scaling and normalization

Distance-based and gradient-based algorithms — k-nearest neighbors, support vector machines, neural networks — are sensitive to feature scale; a column ranging 0–1,000,000 will dominate one ranging 0–1 regardless of which actually matters more. Min-max scaling rescales features to a fixed range, typically 0–1. Standardization (z-score scaling) centers features at a mean of 0 with a standard deviation of 1, which suits algorithms that assume roughly normal data. Scaling by median and IQR — RobustScaler in scikit-learn — uses the median and interquartile range instead of the mean and standard deviation, which keeps a handful of extreme outliers from compressing the rest of the data into a narrow band [8]. Tree-based models (random forests, gradient boosting) split on thresholds rather than distances, so they're largely insensitive to scale and this step can often be skipped for them.

Scaling and Normalization

Building a repeatable data cleaning workflow

A cleaning pass that lives only in a notebook's run history isn't reproducible — the next person, or the same person three months later, can't tell what was done or why. Treating data cleaning as code, not a one-off manual edit, is what makes it auditable.

Exploratory data analysis (EDA) is step zero, not an afterthought: profiling column types, null rates, value distributions, and obvious anomalies before deciding which cleaning steps a dataset actually needs. Skipping straight to cleaning without this step means guessing at problems instead of measuring them.

Pandas covers most of the cleaning operations directly — isnull(), fillna(), drop_duplicates() — and scikit-learn covers the preprocessing transformations that follow, with its Pipeline object chaining imputers, encoders, and scalers into a single fit/transform unit that runs identically on training and new data [9]. Version-controlling the cleaning script (not just the cleaned output file) and logging which rows were dropped, imputed, or capped — and why — turns a one-time fix into something the next person can rerun and check.

Building a Repeatable Data Cleaning Workflow

Avoiding data leakage and common pitfalls

Data leakage happens when information that wouldn't be available at prediction time leaks into training, and the most common cause is a cleaning or scaling step run before the train/test split instead of after. Fitting a scaler or an imputer on the full dataset means the test set's statistics — its mean, its range, its missing-value pattern — quietly influence how the training data gets transformed.

The fix is mechanical: fit every cleaning and preprocessing step on the training data only, then apply that same fitted transformation to validation and test data without refitting [9]. A scikit-learn Pipeline enforces this by construction, since each step's fit() only ever sees the data it's called on. The symptom of skipped leakage prevention is a model that posts strong validation metrics and then underperforms in production — the model never learned to generalize, because evaluation never tested it on truly unseen statistics in the first place. Target leakage is a related but distinct mistake: a feature that encodes the outcome itself, such as a "cancellation date" column present only for customers who already churned.

Avoiding Data Leakage and Common Pitfalls

Real-world applications across industries

A retailer building customer segments needs purchase and demographic records cleaned first — duplicate customer IDs from a merged loyalty database, missing income fields, and inconsistent product category labels all distort which cluster a customer lands in before any clustering algorithm runs.

In manufacturing, predictive maintenance models depend on sensor data that arrives with dropped readings, transmission noise, and occasional out-of-range spikes from a faulty sensor rather than a real fault; a 2025 study on IoT-based predictive maintenance at container terminals applied cleaning and structuring to condition-monitoring data before training models to flag equipment failures ahead of breakdown [10].

In finance, fraud detection models face a structural cleaning challenge: fraud cases are rare and statistically extreme by definition, so the outlier-removal habits that help other models can strip out exactly the cases the model needs to learn from. A 2025 study on credit card fraud detection addressed this by combining feature selection methods to retain the signal in a small set of genuinely informative, cleaned features rather than removing the rare-event rows entirely [11].

Conclusion and next steps

Data cleaning is the step that decides whether a model learns the pattern in the business problem or the pattern in the data's mistakes. Missing-value handling, outlier treatment, deduplication, encoding, and scaling each correct a different failure mode, and skipping the workflow and version-control habits around them turns a one-time fix into a problem that resurfaces with every new data batch.

If the raw data behind a model still needs structured labeling rather than just cleaning — start here

Insights into the Digital World

Datasets

What is Data Cleaning in Machine Learning?

Robotics

NVIDIA Isaac Sim for Robot Training: A Complete Guide

Datasets

What Is Crowdsourcing? Complete Guide

AI Training, Data Labeling

What Is 3D LiDAR SLAM Technology? How It Works and Where It’s Used 

Datasets

Structured vs. Unstructured Data: A Data Expert’s Guide to Maximizing Business Value

Datasets

Qualitative Data Collection Methods: A Practical Guide for ML and Product Teams

Datasets

How to Collect Data for Machine Learning: A Practical Guide for ML Teams

Robotics

Robot Arm Training: A Complete Guide

Ready to get started?

Tell us what you need — we’ll reply within 24h with a free estimate

    What service are you looking for? *
    What service are you looking for?
    Data Labeling
    AI Model Testing
    Data Collection
    Ready-made Datasets
    Human Moderation
    Medicine
    Other
    What's your budget range? *
    What's your budget range?
    < $5,000
    $5,000 – $25,000
    $25,000 – $50,000
    $50,000 – $100,000
    $100,000+
    Not sure yet
    • United States+1
    • United Kingdom+44
    • Afghanistan (‫افغانستان‬‎)+93
    • Albania (Shqipëri)+355
    • Algeria (‫الجزائر‬‎)+213
    • American Samoa+1684
    • Andorra+376
    • Angola+244
    • Anguilla+1264
    • Antigua and Barbuda+1268
    • Argentina+54
    • Armenia (Հայաստան)+374
    • Aruba+297
    • Australia+61
    • Austria (Österreich)+43
    • Azerbaijan (Azərbaycan)+994
    • Bahamas+1242
    • Bahrain (‫البحرين‬‎)+973
    • Bangladesh (বাংলাদেশ)+880
    • Barbados+1246
    • Belarus (Беларусь)+375
    • Belgium (België)+32
    • Belize+501
    • Benin (Bénin)+229
    • Bermuda+1441
    • Bhutan (འབྲུག)+975
    • Bolivia+591
    • Bosnia and Herzegovina (Босна и Херцеговина)+387
    • Botswana+267
    • Brazil (Brasil)+55
    • British Indian Ocean Territory+246
    • British Virgin Islands+1284
    • Brunei+673
    • Bulgaria (България)+359
    • Burkina Faso+226
    • Burundi (Uburundi)+257
    • Cambodia (កម្ពុជា)+855
    • Cameroon (Cameroun)+237
    • Canada+1
    • Cape Verde (Kabu Verdi)+238
    • Caribbean Netherlands+599
    • Cayman Islands+1345
    • Central African Republic (République centrafricaine)+236
    • Chad (Tchad)+235
    • Chile+56
    • China (中国)+86
    • Christmas Island+61
    • Cocos (Keeling) Islands+61
    • Colombia+57
    • Comoros (‫جزر القمر‬‎)+269
    • Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)+243
    • Congo (Republic) (Congo-Brazzaville)+242
    • Cook Islands+682
    • Costa Rica+506
    • Côte d’Ivoire+225
    • Croatia (Hrvatska)+385
    • Cuba+53
    • Curaçao+599
    • Cyprus (Κύπρος)+357
    • Czech Republic (Česká republika)+420
    • Denmark (Danmark)+45
    • Djibouti+253
    • Dominica+1767
    • Dominican Republic (República Dominicana)+1
    • Ecuador+593
    • Egypt (‫مصر‬‎)+20
    • El Salvador+503
    • Equatorial Guinea (Guinea Ecuatorial)+240
    • Eritrea+291
    • Estonia (Eesti)+372
    • Ethiopia+251
    • Falkland Islands (Islas Malvinas)+500
    • Faroe Islands (Føroyar)+298
    • Fiji+679
    • Finland (Suomi)+358
    • France+33
    • French Guiana (Guyane française)+594
    • French Polynesia (Polynésie française)+689
    • Gabon+241
    • Gambia+220
    • Georgia (საქართველო)+995
    • Germany (Deutschland)+49
    • Ghana (Gaana)+233
    • Gibraltar+350
    • Greece (Ελλάδα)+30
    • Greenland (Kalaallit Nunaat)+299
    • Grenada+1473
    • Guadeloupe+590
    • Guam+1671
    • Guatemala+502
    • Guernsey+44
    • Guinea (Guinée)+224
    • Guinea-Bissau (Guiné Bissau)+245
    • Guyana+592
    • Haiti+509
    • Honduras+504
    • Hong Kong (香港)+852
    • Hungary (Magyarország)+36
    • Iceland (Ísland)+354
    • India (भारत)+91
    • Indonesia+62
    • Iran (‫ایران‬‎)+98
    • Iraq (‫العراق‬‎)+964
    • Ireland+353
    • Isle of Man+44
    • Israel (‫ישראל‬‎)+972
    • Italy (Italia)+39
    • Jamaica+1876
    • Japan (日本)+81
    • Jersey+44
    • Jordan (‫الأردن‬‎)+962
    • Kazakhstan (Казахстан)+7
    • Kenya+254
    • Kiribati+686
    • Kosovo+383
    • Kuwait (‫الكويت‬‎)+965
    • Kyrgyzstan (Кыргызстан)+996
    • Laos (ລາວ)+856
    • Latvia (Latvija)+371
    • Lebanon (‫لبنان‬‎)+961
    • Lesotho+266
    • Liberia+231
    • Libya (‫ليبيا‬‎)+218
    • Liechtenstein+423
    • Lithuania (Lietuva)+370
    • Luxembourg+352
    • Macau (澳門)+853
    • Macedonia (FYROM) (Македонија)+389
    • Madagascar (Madagasikara)+261
    • Malawi+265
    • Malaysia+60
    • Maldives+960
    • Mali+223
    • Malta+356
    • Marshall Islands+692
    • Martinique+596
    • Mauritania (‫موريتانيا‬‎)+222
    • Mauritius (Moris)+230
    • Mayotte+262
    • Mexico (México)+52
    • Micronesia+691
    • Moldova (Republica Moldova)+373
    • Monaco+377
    • Mongolia (Монгол)+976
    • Montenegro (Crna Gora)+382
    • Montserrat+1664
    • Morocco (‫المغرب‬‎)+212
    • Mozambique (Moçambique)+258
    • Myanmar (Burma) (မြန်မာ)+95
    • Namibia (Namibië)+264
    • Nauru+674
    • Nepal (नेपाल)+977
    • Netherlands (Nederland)+31
    • New Caledonia (Nouvelle-Calédonie)+687
    • New Zealand+64
    • Nicaragua+505
    • Niger (Nijar)+227
    • Nigeria+234
    • Niue+683
    • Norfolk Island+672
    • North Korea (조선 민주주의 인민 공화국)+850
    • Northern Mariana Islands+1670
    • Norway (Norge)+47
    • Oman (‫عُمان‬‎)+968
    • Pakistan (‫پاکستان‬‎)+92
    • Palau+680
    • Palestine (‫فلسطين‬‎)+970
    • Panama (Panamá)+507
    • Papua New Guinea+675
    • Paraguay+595
    • Peru (Perú)+51
    • Philippines+63
    • Poland (Polska)+48
    • Portugal+351
    • Puerto Rico+1
    • Qatar (‫قطر‬‎)+974
    • Réunion (La Réunion)+262
    • Romania (România)+40
    • Russia (Россия)+7
    • Rwanda+250
    • Saint Barthélemy+590
    • Saint Helena+290
    • Saint Kitts and Nevis+1869
    • Saint Lucia+1758
    • Saint Martin (Saint-Martin (partie française))+590
    • Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)+508
    • Saint Vincent and the Grenadines+1784
    • Samoa+685
    • San Marino+378
    • São Tomé and Príncipe (São Tomé e Príncipe)+239
    • Saudi Arabia (‫المملكة العربية السعودية‬‎)+966
    • Senegal (Sénégal)+221
    • Serbia (Србија)+381
    • Seychelles+248
    • Sierra Leone+232
    • Singapore+65
    • Sint Maarten+1721
    • Slovakia (Slovensko)+421
    • Slovenia (Slovenija)+386
    • Solomon Islands+677
    • Somalia (Soomaaliya)+252
    • South Africa+27
    • South Korea (대한민국)+82
    • South Sudan (‫جنوب السودان‬‎)+211
    • Spain (España)+34
    • Sri Lanka (ශ්‍රී ලංකාව)+94
    • Sudan (‫السودان‬‎)+249
    • Suriname+597
    • Svalbard and Jan Mayen+47
    • Swaziland+268
    • Sweden (Sverige)+46
    • Switzerland (Schweiz)+41
    • Syria (‫سوريا‬‎)+963
    • Taiwan (台灣)+886
    • Tajikistan+992
    • Tanzania+255
    • Thailand (ไทย)+66
    • Timor-Leste+670
    • Togo+228
    • Tokelau+690
    • Tonga+676
    • Trinidad and Tobago+1868
    • Tunisia (‫تونس‬‎)+216
    • Turkey (Türkiye)+90
    • Turkmenistan+993
    • Turks and Caicos Islands+1649
    • Tuvalu+688
    • U.S. Virgin Islands+1340
    • Uganda+256
    • Ukraine (Україна)+380
    • United Arab Emirates (‫الإمارات العربية المتحدة‬‎)+971
    • United Kingdom+44
    • United States+1
    • Uruguay+598
    • Uzbekistan (Oʻzbekiston)+998
    • Vanuatu+678
    • Vatican City (Città del Vaticano)+39
    • Venezuela+58
    • Vietnam (Việt Nam)+84
    • Wallis and Futuna (Wallis-et-Futuna)+681
    • Western Sahara (‫الصحراء الغربية‬‎)+212
    • Yemen (‫اليمن‬‎)+967
    • Zambia+260
    • Zimbabwe+263
    • Åland Islands+358
    Where did you hear about Unidata? *
    Where did you hear about Unidata?
    Andrew
    Head of Client Success

    — I'll guide you through every step, from your first
    message to full project delivery

    Thank you for your
    message

    It has been successfully sent!

    We use cookies to enhance your experience, personalize content, ads, and analyze traffic. By clicking 'Accept All', you agree to our Cookie Policy.