Skip to content
Pixel
العربية

5-2Unit 5 · Data Collection and Cleaning

Data Cleaning and Transformation

11 min readStart exercises
In this lesson
  1. The Big Idea
  2. Why Clean and Transform Data Before Analysis?
  3. Handling Missing Values
  4. Outliers and Duplicate Records
  5. Data Type Conversion and Unifying Formats
  6. Normalization and Standardization
  7. Reshaping Data: Pivot, Join and Aggregation
  8. Try It Yourself
  9. Common Mistakes
  10. Key Points
  11. FAQ

The Big Idea

Real data rarely arrives ready to use: an empty cell here, an impossible number there, a row typed in twice, dates written three different ways. Before any analysis can be trusted, the data needs data cleaning, finding its problems and dealing with them, and data transformation, preparing its formats and structure to fit the question. The rule behind this whole lesson is garbage in, garbage out: exact calculations on flawed data still give a flawed answer.

Why Clean and Transform Data Before Analysis?

Whether your data is primary or secondary, it may need two kinds of work before analysis:

  • Data cleaning: finding the data's problems, such as missing, outlying and duplicate values, then correcting them or handling them appropriately.
  • Data transformation: preparing the formats or structure so they fit the question and the analysis method, for example unifying date formats, changing the scale or rearranging a table.

The quality of this preparation strongly affects the quality of the results. But note: there is no single chain of fixes that suits all data. Every decision depends on the type of problem and the analysis question, and needs a reason and a check of its effect.

Preparing data before analysis Four boxes joined by arrows. Collect: from surveys, open data and APIs. Clean: a small table of names and ages; Ali's age is missing (highlighted yellow), Mona's row appears twice (highlighted purple), and Hoda's age of 170 is an outlier (highlighted red); the task is to find and handle these problems. Transform: examples such as rescaling so the minimum becomes 0 and the maximum 1, turning the text "123" into the number 123, using one date format and reshaping the table. Analyse: statistics, charts and machine learning. At the bottom: garbage in, garbage out; exact maths on flawed data still gives a flawed answer. From raw data to analysis 1) Collect Surveys Open data API 2) Clean 3) Transform 4) Analyse Statistics Charts Machine learning Name Age Mona 17 Ali ? Mona 17 Hoda 170 3 problems highlighted Find & handle problems min→0 max→1 Type: "123" → 123 One date format 0–1 scale if needed Reshape the table Fit format & structure Garbage in, garbage out: exact maths on flawed data still gives a flawed answer
Cleaning and transformation sit between collection and analysis, and their quality limits everything after them.

Handling Missing Values

A missing value is a cell that should hold a value but is empty. Missing values can break some calculations or change results, depending on how many there are, why they are missing and their pattern. Common ways to handle them:

| Response | What do we do? | When does it fit? | |---|---|---| | Deletion | Remove the record (row) or the variable (column) | When little is missing, and dropping records loses no important information and adds no important bias | | Imputation | Estimate a replacement value appropriately, simply (e.g. the median) or with a more advanced method | After understanding why values are missing, their pattern and the analysis method, and checking the effect on the distribution and results | | Flagging | Create an indicator showing the value was missing, or a category for it | When the absence itself means something, such as a person refusing to answer |

The choice depends on the amount, cause and pattern of the gaps and the purpose of the analysis. One of the book's most important warnings is that simple mean imputation can change the distribution of the data and reduce its variance, especially when a lot is missing.

Why does variance shrink? Imagine a column with three known values, 10, 12 and 14, and two missing ones. The known mean is 12. If you fill both gaps with 12, you now have five values, two of them sitting exactly in the middle, so the data looks less spread out than it really is. And if most of the column is missing, you are effectively inventing look-alike data and treating it as real.

Outliers and Duplicate Records

Outliers

An outlier is a value that is far from most of the others, but it is not necessarily an error. It may come from an entry or measurement mistake, in which case it is called an abnormal value, or it may be a real but rare value. So you check where the value came from and how the variable is defined before changing anything.

Handling always starts with finding the cause:

  1. If the cause is an entry or measurement error: correct the value or delete it. Example: a secondary student aged "170" years; most likely their height was typed into the age column.
  2. If the value is genuine: do not delete it just because it is far from the rest; decide according to the analysis question, with a clear analytical reason. Example: a huge sales day at a stationery shop in the first week of school may be completely real, and deleting it would hide the most important thing in the data.

Duplicate records

Duplicate records can distort calculations, for example a sale counted twice inflates the total. But the golden rule is: only delete an apparent duplicate once you are sure it is an unintended repeat of the same observation or event. Similar records can be separate real events: a student who bought two pens at the canteen on the same day in two separate purchases produces two correct records, even though they look alike.

Cleaning decisions: missing values, outliers and duplicates Two panels. First: missing value? Decide by the amount, cause and pattern of the gaps and the purpose of the analysis. There are three responses: delete, when little is missing, no bias is added and nothing important is lost; impute, by estimating a replacement such as the median and then checking its effect on the distribution; flag, when the gap itself means something, for example a refusal to answer. Second: outlier? Find the cause first. If it is an entry or measurement error, correct it or delete it; if it is a real but rare value, do not drop it just for being far from the rest, and decide by the analysis question, after checking the source and the variable's definition. At the bottom: remove a duplicate only once you are sure it is one event recorded twice, not two similar events. Missing value? Decide by amount, cause, pattern, purpose Delete Little is missing, no bias added and nothing important is lost Impute Estimate a value, e.g. median then check its effect Flag When the gap itself means something, e.g. refused Outlier? Find the cause first Entry or measurement error A real value, just rare Correct it or delete it Don't drop it just for being far Check the source and the definition Duplicate? Remove it only once you are sure it is one event recorded twice, not two similar events
Every fix is a decision: ask about the cause before you delete or fill anything.

Data Type Conversion and Unifying Formats

The Arabic edition separates two things that data may need together or separately:

  • Changing the data type: for example turning text that contains digits into an actual number.
  • Unifying formats or encodings: for example writing all dates the same way, or merging category values written in more than one way.

| Conversion | Description | Example | |---|---|---| | Text to number | Turn numbers stored as text into numeric values that can be calculated with | The text "123" becomes the number 123 | | Unify date format | Put dates written in different formats into one format | 2026/4/1 and 01 Apr 2026 become 2026-04-01 | | Unify spelling | Merge values with the same meaning into one spelling | A mix of "Male/Female" and "M/F" unified to "Male/Female" |

Why does this matter? Because software does not understand meaning the way you do. If formats or codes differ, it may treat similar values as different: "M" and "Male" show up as two categories in a chart. And if numbers are stored as text, some calculations may fail, or the tool may treat them as text that cannot be added up. So check types and formats before analysis, depending on the tool you use.

Normalization and Standardization

In some scale-sensitive algorithms, a variable with a larger range can have more influence simply because its numbers are bigger. For example, height in centimetres (numbers around 160 to 180) and weight in kilograms (numbers around 50 to 80): the difference between two students in height can look "bigger" only because the numbers are bigger. Here you use a suitable scaling method.

| Method | What does it do? | Purpose | |---|---|---| | Normalization / Min–Max scaling | Converts values to a range from 0 to 1 using the smallest and largest value in the data | Puts variables on similar ranges when the algorithm needs that | | Standardization | Converts values so their mean is 0 and their standard deviation is 1 | Expresses how far a value is from the mean in units of standard deviation |

Min–Max scaling with numbers

The idea: the smallest value becomes 0, the largest becomes 1, and every other value takes its relative position in between. Subtract the minimum from the value, then divide by the range (maximum minus minimum):

x' = (x − min) / (max − min)

Example: three students weigh 50, 62 and 80 kg. The minimum is 50, the maximum is 80, and the range is 30.

  • 50 becomes (50 − 50) ÷ 30 = 0
  • 62 becomes (62 − 50) ÷ 30 = 12 ÷ 30 = 0.4
  • 80 becomes (80 − 50) ÷ 30 = 1

Note that 0.4 does not mean "40 kg"; it means the weight sits 40% of the way from the lightest to the heaviest student in this data.

Standardization

Standardization subtracts the mean from each value, then divides by the standard deviation. The data used in the calculation then has a mean of 0 and a standard deviation of 1. The new value means: how many standard deviations is this value from the mean? Example: if a class's mean score is 70 and the standard deviation is 10, a score of 85 becomes (85 − 70) ÷ 10 = 1.5, one and a half standard deviations above the mean. How you interpret that number depends on the shape of the distribution.

Reshaping Data: Pivot, Join and Aggregation

Reshaping data means changing a table's structure, combining tables, or summarising them to fit the question. Its key operations:

| Operation | Description | Example | |---|---|---| | Pivot | Convert data between long and wide format according to chosen rows and columns | Sales stored one row per (day, item) become a "day × item" table | | Join | Combine data from several tables using a key or matching condition | Link the student register and the marks sheet through "student ID" | | Aggregation | Calculate totals, averages and so on for each group and summarise | Compute monthly totals from daily sales |

Pivot from long format to wide format On one side, a long table of school canteen sales with three columns, day, item and sales, and six rows where each day appears twice: Sunday juice 40, Sunday sandwich 25, Monday juice 35, Monday sandwich 30, Tuesday juice 50, Tuesday sandwich 20. An arrow labelled Pivot leads to a wide table with one row per day and one column per item: Sunday 40 and 25, Monday 35 and 30, Tuesday 50 and 20. Below it an aggregation bar: juice total 125, sandwich total 75. At the bottom: same values, different shape; each cell of the wide table holds one value for one day and item. Pivot: from long format to wide format Before: long (day repeats) Day Item Sales Sun Juice 40 Sun Sandwich 25 Mon Juice 35 Mon Sandwich 30 Tue Juice 50 Tue Sandwich 20 Pivot After: wide (day × item) Day Juice Sandwich Sun 40 25 Mon 35 30 Tue 50 20 Aggregate: Juice = 125, Sandwich = 75 Same values, different shape: each wide cell = one value for one day and item
Pivot changes the shape, not the values; aggregation summarises the values into one number per group.

Long format and wide format

In long format the day repeats across several rows, because each row holds one value for one item. That is convenient for recording sales day by day. In wide format each day gets one row and each item gets a column, so the manager can read the week's sales at a glance. The values themselves have not changed, only their arrangement.

Joining with a key

Picture two tables: the first has "student ID", name and class; the second has "student ID" and maths mark. A join places each mark next to its owner's name using the shared column "student ID". Choosing the key matters: two students can share a name, but the student ID identifies each student uniquely.

Aggregation

Aggregation summarises: from 30 rows of daily sales to one row for the month holding the total or the average. Which operation do you choose? It depends on the purpose of the analysis. If you want to see monthly sales trends, you need to aggregate daily sales by month. Make the purpose clear first, then plan the reshaping.

Try It Yourself

Try
Try Min–Max scaling yourself
min = 50, max = 80, max − min = 30
x′ = (x − min) / (max − min)
Value x(x − min) / (max − min)Scaled x′
50(50 − 50) / 300
62(62 − 50) / 300.4
80(80 − 50) / 301
The smallest value becomes 0, the largest becomes 1, and every other value takes its relative position in between.
0, 0.4, 1
Try
What kind of data problem is it?
In a survey table about daily screen time, sort each problem by its type.
Items (8)
Tap an item to select it, then tap the category it belongs to.
Nothing here yet
Nothing here yet
Nothing here yet
Nothing here yet
Try
9999 hours of screen time!
The situation
Your class is analysing a survey on daily screen time. Most answers are between 1 and 6 hours, but one cell says 9999. A classmate says: 'Delete it now, it's obviously wrong.' What do you do?
What would you do? You can try more than one choice.

Common Mistakes

"Every outlier is an error and must be deleted"

An outlier is far from most values, but it may be real and rare, like a huge sales day at the start of the school year.

Find the cause first: errors are corrected or deleted; genuine values are not dropped just for being far, and you decide according to the analysis question.

"Filling blanks with the mean is always safe"

Simple mean imputation can change the distribution and reduce variance, and if most of the column is empty, you are inventing data.

Choose between deletion, imputation and flagging based on the amount, cause and pattern of the gaps, then check how your choice affects the results.

"Any two similar rows are a duplicate to delete"

Two similar rows may be two separate real events, like two purchases of the same product on the same day.

Remove a duplicate only once you are sure it is an unintended repeat of the same event.

"Normalization and standardization are the same thing"

Normalization (Min–Max) puts values in a 0 to 1 range; standardization gives a mean of 0 and a standard deviation of 1, and its values mean "how many standard deviations from the mean".

"0 to 1" → Min–Max. "Mean 0, standard deviation 1" → standardization. Both are used when the algorithm is scale-sensitive.

"Pivot and aggregation are the same operation"

Pivot rearranges the same values from long to wide without summarising them; aggregation computes a total or average for each group.

"One row per day, one column per product" → pivot. "Total for each month" → aggregation. Sometimes you need both.

Key Points

  • Cleaning finds and handles problems in the data; transformation prepares formats and structure for the question. There is no single fix chain for all data: garbage in, garbage out.
  • Missing values: delete, impute or flag, depending on amount, cause, pattern and purpose; mean imputation can change the distribution and reduce variance.
  • Outliers: start with the cause; errors are corrected or deleted, and real rare values are not dropped just for being far away.
  • Duplicate records are removed only once you are sure they are unintended repeats of the same event.
  • Separate changing the data type (text to number) from unifying formats and encodings (dates, "Male"/"M").
  • Min–Max scaling converts values to 0–1; standardization gives mean 0 and standard deviation 1; both serve scale-sensitive algorithms, not every analysis.
  • Reshaping: pivot (long ↔ wide), join (tables via a shared key) and aggregation (a summary per group), chosen according to the purpose of the analysis.

FAQ

What is the difference between data cleaning and data transformation?

Cleaning fixes problems in the data itself: missing, outlying or duplicate values. Transformation does not assume the data is wrong; it changes the format or structure to fit the question, such as unifying dates, scaling or reshaping a table.

When should I use Min–Max scaling?

When you use a scale-sensitive algorithm and your variables have very different ranges, like height in centimetres and weight in kilograms, so that one does not dominate just because its numbers are bigger. It is not needed for every analysis; a simple average does not need it.

Should I delete a row that has a missing value?

It depends on the amount, cause and pattern of the missing data. If little is missing, at random, and deleting adds no bias, deletion may fit. If a lot is missing or it is concentrated in one group, deletion can lose important information. If the absence has a meaning, such as a refusal to answer, flag it.

What does garbage in, garbage out mean?

No analysis, however careful, can fix flawed data. If a value like 9999 hours goes into an average, the average will be misleading even though the calculation is correct. That is why preparing data matters as much as the analysis itself.

Done reading? Test yourself