> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Introduction to Data Transformation and Cleaning

> Overview of data cleaning and transformation techniques for preparing datasets for reliable machine learning, including AWS tools and practical examples.

Models only learn from the data you provide. If that data is inaccurate, inconsistent, or full of errors, the model will be unreliable. In short: bad data equals bad models. Data cleaning and transformation are essential steps that prevent poor-quality data from undermining the entire machine learning pipeline.

Data cleaning identifies and fixes problems such as missing values, inconsistent formats, duplicates, outliers, and type mismatches. Once cleaned, data is transformed to meet algorithm requirements (scaling, encoding, aggregation, parsing, binning), producing a reliable foundation for feature engineering and modeling.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-cleaning-process-issues-outline.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=d118ea0043db6e79120d300aa883af07" alt="The image outlines the process of data cleaning, highlighting issues such as missing values, inconsistent formats, duplicates, and outliers in datasets." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-cleaning-process-issues-outline.jpg" />
</Frame>

<Callout icon="lightbulb" color="#1CB2FE">
  Clean, well-documented data is the first and most important step toward building reliable ML systems. Invest time here to avoid compounding issues downstream.
</Callout>

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-cleaning-issues-explained.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=f6a20134a391294dfa1ac88b3f0e7965" alt="The image explains data cleaning, detailing issues like missing values, inconsistent formats, duplicates, outliers, and data type mismatches in datasets." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-cleaning-issues-explained.jpg" />
</Frame>

Quick reference — common problems and actions

| Problem                     | Typical fixes                                                           |
| --------------------------- | ----------------------------------------------------------------------- |
| Missing values              | Drop rows/columns, impute (mean/median/mode), or model-based imputation |
| Duplicates                  | Remove exact duplicates or dedupe based on key subset                   |
| Inconsistent formats        | Parse and normalize (e.g., dates to ISO 8601)                           |
| Outliers                    | Detect with IQR/domain thresholds; cap, transform, or remove            |
| Type mismatches             | Strip non-numeric characters and cast to numeric/datetime               |
| Categorical inconsistencies | Map variants/typos to a controlled vocabulary                           |

Common cleaning techniques (expanded)

* Missing values: remove or impute (median is robust for skewed data).
* Duplicates: deduplicate using full-row or subset-based logic.
* Outliers: apply domain thresholds, IQR, or winsorization.
* Type conversions: ensure numeric, datetime, and categorical dtypes are correct.
* Standardization: normalize inconsistent string formats (dates, currencies).
* Controlled vocabulary: normalize typos and synonyms to canonical category values.

Missing values
Missing values can distort statistics and models. Choose between removing affected rows/columns (simpler, destructive) or imputing (preserves sample size). Imputation methods include mean, median, mode, forward/backfill, or model-based techniques.

<Callout icon="warning" color="#FF6B6B">
  Dropping rows with missing values is irreversible for that dataset copy and can bias results if missingness is not random. Prefer imputation or analyze missingness patterns first.
</Callout>

Example — drop or impute with pandas:

```python theme={null}
import pandas as pd

df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [29, None, 45]
})

# Drop rows with any missing values
df_dropped = df.dropna()

# Fill missing Age with median (robust to skew)
median_age = df["Age"].median()
df_filled = df.copy()
df_filled["Age"] = df_filled["Age"].fillna(median_age)
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/before-after-missing-values-age-comparison.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=8e2027c993488192c2003897470a8c5b" alt="The image shows a comparison of tables labeled &#x22;Before&#x22; and &#x22;After&#x22; addressing missing values in the &#x22;Age&#x22; column, where a missing age value is filled with the median (37)." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/before-after-missing-values-age-comparison.jpg" />
</Frame>

Inconsistent formats
Canonicalizing formats (especially dates and numeric strings) prevents parsing errors and ensures consistent sorting, filtering, and aggregation. Use robust parsing functions that can coerce invalid values to null for later inspection.

Example — parse dates and format as ISO 8601 with pandas:

```python theme={null}
df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce", infer_datetime_format=True)
# To format as ISO string:
df["timestamp_iso"] = df["timestamp"].dt.strftime("%Y-%m-%dT%H:%M:%S")
```

Duplicates
Duplicates inflate counts and skew model training. Remove exact duplicates or deduplicate using a subset of columns (e.g., id + timestamp), depending on the domain.

```python theme={null}
# Remove exact duplicate rows
df_unique = df.drop_duplicates()

# Remove duplicates based on subset of columns (e.g., id and timestamp)
df_unique_subset = df.drop_duplicates(subset=["id", "timestamp"])

# In-place single-line usage
df.drop_duplicates(inplace=True)
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/spelling-inconsistencies-country-names-table.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=279136839c3b4dd1e5ac65b01cf4b123" alt="The image shows a table highlighting spelling/typo inconsistencies for country names associated with employee IDs. It suggests mapping these values to a controlled vocabulary for uniformity." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/spelling-inconsistencies-country-names-table.jpg" />
</Frame>

Typos and inconsistent categorical values
Create a controlled vocabulary (mapping table) to normalize synonyms, abbreviations, and typos into a single canonical value. This improves feature consistency and reduces cardinality.

Example mapping:

```python theme={null}
mapping = {
    "US": "United States",
    "USA": "United States",
    "United States of America": "United States",
    "U.S.": "United States"
}
df["country_clean"] = df["country"].replace(mapping)
```

Outliers
Outliers can be legitimate or erroneous. Detect with domain thresholds, Z-score, or IQR. Handling strategies include removing, capping, or transforming the values.

Example — winsorization by clipping to 1st and 99th percentiles:

```python theme={null}
low, high = df["value"].quantile([0.01, 0.99])
df["value_clipped"] = df["value"].clip(lower=low, upper=high)
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/temperature-outlier-replacement-table.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=6d1acedae398d99e6cda05d1655bbc69" alt="The image shows a table with &#x22;Before&#x22; and &#x22;After&#x22; columns illustrating how a temperature outlier (999°C) for SensorID S2 is replaced with a more realistic value (25°C). It suggests flagging and replacing extreme values using domain thresholds." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/temperature-outlier-replacement-table.jpg" />
</Frame>

Data type mismatches
Numeric values sometimes contain currency symbols, commas, or other non-numeric characters. Strip those characters and cast to numeric or datetime types. Coerce invalid parses to NaN for later handling.

Example — clean dollar amounts and convert to numeric:

```python theme={null}
import pandas as pd

# Remove non-numeric characters and convert to numeric (coerce errors to NaN)
df["price_clean"] = pd.to_numeric(
    df["price"].astype(str)
        .str.replace(r"[^\d\.\-]", "", regex=True)
        .replace("", pd.NA),
    errors="coerce"
)
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-table-comparison-temperature-format.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=279acffaa6d50b86e25c9fdaa8a4af6d" alt="The image shows a before-and-after comparison of a data table where non-numeric characters are stripped from a temperature column, converting it to a consistent float format." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-table-comparison-temperature-format.jpg" />
</Frame>

Data transformation
Cleaning fixes errors; transformation prepares features for learning algorithms. Typical transformations include scaling, encoding, aggregation, parsing, and binning.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-transformation-techniques-scaling-encoding.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=843666dd60e8108b7cd4765e64c4253e" alt="The image describes four common data transformation techniques: scaling, encoding, aggregation, and date parsing. Each technique includes a brief explanation and an associated icon." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-transformation-techniques-scaling-encoding.jpg" />
</Frame>

Key transformation techniques

* Scaling / Normalization\
  Rescale numeric features so ones with large ranges don’t dominate models. Use Min-Max scaling to rescale to \[0, 1], or standardization (Z-score) to center to mean 0 and unit variance.

Example with scikit-learn:

```python theme={null}
from sklearn.preprocessing import MinMaxScaler, StandardScaler

scaler = MinMaxScaler()
df[["feature1_scaled"]] = scaler.fit_transform(df[["feature1"]])

std = StandardScaler()
df[["feature1_std"]] = std.fit_transform(df[["feature1"]])
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-normalization-min-max-scaling.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=0da89a1e1211ff23f43b5d16eee6cfeb" alt="The image illustrates data normalization using Min-Max Scaling, converting a range from 20-100 to a standardized range of 0-1." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/data-normalization-min-max-scaling.jpg" />
</Frame>

* Encoding categorical variables\
  Choose encoding based on model and cardinality:
  * One-hot encoding: creates binary columns per category (good for nominal features).
  * Label encoding: assigns integer codes (useful for ordinal or tree-based models).

Examples:

```python theme={null}
# One-hot (pandas)
df = pd.get_dummies(df, columns=["color"])

# Label encoding (scikit-learn)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df["color_label"] = le.fit_transform(df["color"].astype(str))
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/categorical-variables-encoding-diagram.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=0cf1a6f8be4a98f2b5787699de22c68d" alt="The image illustrates the process of encoding categorical variables by converting text labels (Red, Green, Blue) into numerical form (2, 1, 0)." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/categorical-variables-encoding-diagram.jpg" />
</Frame>

* Binning (discretization)\
  Binning converts continuous variables into discrete intervals to reduce noise or improve interpretability. Use pd.cut for fixed bins or pd.qcut for quantiles.

Example — bin ages into categories:

```python theme={null}
bins = [0, 18, 35, 60, 200]
labels = ["Teen", "Young Adult", "Adult", "Senior"]
df["age_group"] = pd.cut(df["age"], bins=bins, labels=labels, right=True)
```

Note: pd.cut's `right` parameter controls whether the bins include the right edge; adjust `right=True`/`False` or bin edges to match your intended inclusive boundaries.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/binning-ages-categories-discretization.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=2383eccb7f00d5d340dd35e68bcbc028" alt="The image explains binning (discretization) of ages into categories: Teen (0-18), Young Adult (19-35), Adult (36-60), and Senior (60+), illustrating conversion of continuous variables into discrete intervals." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/binning-ages-categories-discretization.jpg" />
</Frame>

Binning simplifies patterns and improves interpretability at the cost of some granularity. Choose bins with domain knowledge or data-driven methods.

AWS tools for cleaning and transformation
AWS offers managed services that streamline cleaning and transformation within ML workflows:

| Service                 | Purpose                                                               |
| ----------------------- | --------------------------------------------------------------------- |
| AWS Glue DataBrew       | Visual, no-code/low-code data cleaning and profiling                  |
| AWS Glue                | Serverless ETL for automated, scalable transformations                |
| Amazon EMR              | Distributed processing (Spark/Hadoop) for large-scale transformations |
| SageMaker Data Wrangler | Integrated data preparation and visualization inside SageMaker        |

* [AWS Glue DataBrew](https://aws.amazon.com/databrew/)
* [AWS Glue](https://aws.amazon.com/glue/)
* [Amazon EMR](https://aws.amazon.com/emr/)
* [SageMaker Data Wrangler](https://aws.amazon.com/sagemaker/data-wrangler/)

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ZSqWi1yu-CB1leDX/images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/aws-tools-cleaning-transforming-data-overview.jpg?fit=max&auto=format&n=ZSqWi1yu-CB1leDX&q=85&s=86894b6f358faba18dbc54bf38f919a2" alt="The image provides an overview of AWS tools for cleaning and transforming data, featuring AWS Glue DataBrew, AWS Glue, Amazon EMR, and Amazon SageMaker Data Wrangler." width="1920" height="1080" data-path="images/AWS-Certified-Machine-Learning-Engineer-Associate/Data-Preparation-for-Machine-Learning-ML/Introduction-to-Data-Transformation-and-Cleaning/aws-tools-cleaning-transforming-data-overview.jpg" />
</Frame>

A typical AWS data-preparation workflow

1. Ingest raw data into Amazon S3 as the storage layer.
2. Use AWS Glue or AWS Glue DataBrew to profile, clean, and transform data.
3. For very large-scale processing, run jobs on Amazon EMR (Spark) or Glue ETL.
4. Load transformed data into SageMaker Data Wrangler or directly into SageMaker for feature engineering and model training.
5. Pass clean, transformed data to the model training environment or downstream analytics.

Summary and best practices

* Start with profiling to identify missing values, duplicates, inconsistent formats, outliers, and type issues.
* Prefer reproducible cleaning steps (notebooks, pipelines, or ETL jobs) so preprocessing can be audited and rerun.
* Use domain rules and statistical methods (imputation, deduplication, type conversion) for cleaning.
* Transform features to match algorithm expectations (scaling, encoding, binning, aggregation, parsing).
* Leverage managed tools (DataBrew, Glue, EMR, SageMaker Data Wrangler) to scale and standardize preparation steps.
* Document every transformation and preserve raw data to enable traceability and robust production deployments.

Further reading and references

* [Pandas Documentation](https://pandas.pydata.org/)
* [Scikit-learn Preprocessing](https://scikit-learn.org/stable/modules/preprocessing.html)
* [AWS Glue](https://aws.amazon.com/glue/)
* [Amazon EMR](https://aws.amazon.com/emr/)
* [SageMaker Data Wrangler](https://aws.amazon.com/sagemaker/data-wrangler/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/aws-machine-learning-associates/module/f6c821d2-a5b8-4946-9a75-624ec2ba0e75/lesson/420acee5-f32e-423b-824d-a60fcf62f151" />
</CardGroup>
