انتقل إلى المحتوى
لندن، المملكة المتحدة · تأسست عام 1994
العربية

Unit 2: Data Wrangling and Exploratory Analysis

How to gather, structure, clean and explore data so that it is fit for analysis, and how to summarise it with the right statistics.

Unit 2 of 5 · about 54 minutes

2.1 Getting, combining and structuring data

Data wrangling, also called data munging or data preparation, is the work of turning raw data into a form that can be analysed reliably. It is unglamorous but essential: the quality of any analysis depends on the quality of the data that goes into it. This lesson covers where data comes from, how to structure it and how to combine sources safely.

Where data comes from

  • Operational systems, such as sales, finance, customer relationship management and HR systems, record transactions as part of everyday business.
  • Data warehouses and data lakes bring data from many systems into a central store designed for analysis.
  • Surveys and forms collect information directly from people.
  • Sensors and logs record activity from equipment, websites and apps.
  • External sources include official statistics, open government data and data purchased from third parties.

For each source, find out how and why the data was collected, how often it is updated and who is responsible for it. Data collected for one purpose may not be suitable for another. A field that staff fill in carelessly because nobody uses it is unlikely to be reliable.

Metadata and data dictionaries

Metadata is data about data: what each field means, its units, permitted values and source. A data dictionary records this information in one place. If none exists, creating a simple one as you work is valuable for you and for colleagues. Include the field name, a plain description, the data type, units, example values and any known issues.

Tidy data

A widely used set of principles, known as tidy data, makes analysis much easier:

  1. each variable forms a column;
  2. each observation forms a row;
  3. each type of observational unit forms a table.

Many real spreadsheets break these rules. A common example is a sales report with one column per month. It is easy to read, but awkward to analyse. Reshaping it into "long" format, with columns for store, month and sales, allows you to filter, group and chart the data easily. Merged cells, totals mixed in with data rows and notes typed into data columns cause similar problems.

Combining data with joins

Analysis often requires combining tables, for example linking orders to customer details. This is done with a join, which matches rows using a shared key, such as a customer ID. The main types are:

  • Inner join: keeps only rows that have a match in both tables.
  • Left join: keeps every row from the first table, adding matching information from the second where it exists and leaving blanks where it does not.
  • Full outer join: keeps every row from both tables.

Joins are a frequent source of silent errors. If customer IDs are formatted differently in two systems, for instance with and without leading zeros, rows will fail to match. If a key is not unique in one table, a join can multiply rows unexpectedly, inflating totals.

Tip: always count rows before and after every join, and check a few matched records by hand. An unexpected change in row count is one of the clearest early signs of a problem.

Aggregating data

Analysis often requires summarising data at a different level, such as total sales per store per month. This is called aggregation or grouping. Be clear about the level of each table you use: mixing a table with one row per order and another with one row per customer, without aggregating appropriately, can lead to double counting.

Common mistakes

  • Assuming that a field means what its name suggests without checking.
  • Combining data from periods when definitions changed, such as a new way of recording customer regions.
  • Using an inner join without realising that unmatched records have been dropped.
  • Copying and pasting data between files by hand, which introduces errors and cannot be reproduced.
  • Using personal data for a new purpose without checking whether this is permitted.

In practice

Choose a spreadsheet or table you work with. Check whether it follows tidy data principles; if not, sketch how it would look in long format. Write a short data dictionary for its five most important columns. If you regularly combine it with another source, identify the key used to match them and test how many rows fail to match. These checks take little time and often reveal issues that have been affecting reports for months.

2.2 Cleaning data and checking quality

Real-world data is messy. People mistype entries, systems record values in different formats, records are duplicated and important fields are left blank. Data cleaning identifies and deals with these problems. Done well, it is careful, documented and proportionate; done badly, it can introduce new errors or quietly bias the results.

Dimensions of data quality

It helps to think about quality under several headings:

  • Accuracy: do values correctly reflect reality?
  • Completeness: are required values present?
  • Consistency: do values agree across records and systems, and use the same formats?
  • Validity: do values fall within permitted ranges and types?
  • Uniqueness: is each real-world item recorded only once?
  • Timeliness: is the data up to date enough for the purpose?

Common problems and approaches

Inconsistent formats. Dates may appear as day-month-year in one source and month-day-year in another. Categories may be spelled differently: "London", "london" and "LDN". Standardise formats and create a mapping for category variants. Be especially careful with dates, as some values can be read either way.

Duplicates. The same customer may appear twice with slightly different spellings. Exact duplicates are easy to remove; near-duplicates require matching rules and judgement. Always check whether apparent duplicates are genuinely the same item before removing them, since two customers may share a name.

Invalid values. Ages of 250, negative prices or dates in the future may indicate errors. Some can be corrected from other information; others need to be set as missing.

Missing values. Blank fields are among the most important problems to handle thoughtfully. First, understand why values are missing. Are they missing at random, for example due to an occasional system fault, or is there a pattern, such as a question that people with certain characteristics tend to skip? The reason affects what you should do.

Options for missing data

  • Leave as missing and report how many values were missing, if the analysis can handle it.
  • Remove rows with missing values. This is simple, but if missingness is related to the outcome, it can bias results.
  • Impute, meaning fill in estimated values, for example using the median or a value predicted from other variables. This keeps more data but can make results look more certain than they are.
  • Create an indicator showing that a value was missing, since the absence itself may carry information.

Remember: never replace missing values with zero unless zero is genuinely correct. A blank in a "number of complaints" field might mean none, or it might mean the information was not recorded.

Outliers

An outlier is a value that is very different from most others. Outliers can be errors, such as a misplaced decimal point, or genuine and important, such as a single very large order. Do not delete outliers automatically. Investigate them, correct those that are clearly errors, and decide how to treat genuine ones. Sometimes the right approach is to report results with and without them.

Documenting decisions

Every cleaning decision should be recorded: what the problem was, how many records were affected and what was done. This allows others to understand and challenge your choices and to rerun the process when new data arrives. Wherever possible, carry out cleaning in code or a recorded process rather than by manually editing cells.

Fixing problems at source

Cleaning the same errors every month is wasteful. Where you find recurring problems, report them to the system owners. Simple changes such as drop-down lists instead of free text, validation rules on forms or clearer guidance for staff entering data can prevent errors from occurring in the first place.

Common mistakes

  • Cleaning data so heavily that it no longer represents reality.
  • Removing all rows with any missing value without considering the impact.
  • Treating every outlier as an error.
  • Failing to record what was changed.

In practice

Run a quick quality check on a dataset you use. For each important column, count missing values, look at the most common and the most unusual values, and check minimum and maximum values for anything impossible. Note what you find under the six quality dimensions. Share the results with the data owner and propose one change at the point of entry that would prevent a recurring problem.

2.3 Exploratory data analysis and descriptive statistics

Exploratory data analysis (EDA) is the process of getting to know a dataset before drawing conclusions from it. It combines summary statistics and charts to reveal patterns, relationships, anomalies and problems. Good exploration often answers the question directly, and when it does not, it guides the choice of further analysis.

Measures of centre

  • The mean is the sum of values divided by the number of values. It uses all the data but is pulled strongly by extreme values.
  • The median is the middle value when data is sorted. It is robust to extreme values.
  • The mode is the most common value, most useful for categorical data.

When data is skewed, the mean and median can differ substantially. Incomes, house prices and customer spending are typically right-skewed: most values are modest, but a few are very large. Imagine nine employees earning 30,000 and one earning 300,000. The mean is 57,000, which describes nobody, while the median of 30,000 describes the typical employee well. Reporting both, and explaining the difference, is often the most informative choice.

Measures of spread

Two datasets can have the same average but very different spread. Common measures are:

  • Range: the difference between the largest and smallest value, which is sensitive to outliers.
  • Interquartile range (IQR): the range of the middle half of the data, between the 25th and 75th percentiles. It is robust to outliers.
  • Standard deviation: roughly, the typical distance of values from the mean. For many fairly symmetrical datasets, most values lie within two standard deviations of the mean.

Looking at distributions

Summary statistics can hide important features, so always look at the data visually. A histogram shows how often values fall within ranges, revealing skew, multiple peaks and unusual gaps. A box plot shows the median, IQR and outliers compactly and is useful for comparing groups. For categorical data, a simple bar chart of counts is usually best.

Comparing groups

Much exploration involves comparing a measure across groups: average order value by region, complaint rates by product or delivery times by day of the week. Group comparisons can be revealing, but remember to look at the number of observations in each group. A group with five records may show an extreme average simply by chance.

Relationships between variables

A scatter plot shows the relationship between two numerical variables. The correlation coefficient measures the strength of a straight-line relationship on a scale from -1 to 1, where values near 1 or -1 indicate a strong relationship and values near 0 indicate little linear relationship. Correlation has two important limitations: it only captures straight-line patterns, so a strong curved relationship may show a low value; and correlation does not by itself show causation, a subject covered in the next unit.

Tip: plot before you calculate. Very different datasets can share the same mean, standard deviation and correlation, yet look completely different on a chart.

Changes over time

For data recorded over time, a line chart reveals trends, seasonal patterns and sudden changes. When comparing periods, consider seasonality: comparing December with November in retail will almost always show an increase, so comparing December with the previous December is often more meaningful.

A simple EDA checklist

  1. Check the size of the dataset and what each row represents.
  2. Summarise each variable: counts, missing values, centre and spread, or category frequencies.
  3. Plot the distribution of key variables.
  4. Compare key measures across important groups and over time.
  5. Explore relationships between the main variables.
  6. Note anything surprising and investigate whether it is real or an error.

In practice

Apply the checklist to a dataset you know. Calculate the mean and median of an important numerical variable and explain any difference between them. Draw a histogram and one comparison across groups. Write three short observations in plain language, such as "most orders are under 50, but a small number of very large orders raise the average considerably". Clear observations like these are often exactly what decision-makers need.

Case study: Cleaning membership data at a leisure centre group

Active Borough Leisure, a fictional operator of six leisure centres, wanted to understand why monthly membership cancellations appeared to have risen. An analyst combined membership records from the booking system with cancellation data from the finance system.

The first join produced far fewer matches than expected. Investigation showed that the finance system stored member numbers with a leading letter for one centre, which the booking system omitted. After standardising the format, almost all records matched. The analyst also found around four hundred near-duplicate members, mostly people who had re-joined under new numbers, and decided with the membership manager how to treat them.

Age was missing for about a fifth of members, almost all from one centre that had used a different sign-up form. Rather than filling in values, the analyst reported results with and without that centre.

Exploration showed that cancellations had not risen overall: one centre had moved its cancellation date processing, creating an apparent spike. The analyst documented every step and asked for the sign-up form to be standardised.

Activity

Take a small dataset you have access to, or a public dataset from an official statistics source. Carry out a basic quality check and exploratory analysis using the checklists from this unit. Record three data quality issues, how you handled each, and three plain-language observations about the data.

Compare with a model answer

A good answer briefly describes the dataset, for example monthly energy use for a group of buildings, and states what one row represents. Quality issues are specific: perhaps duplicated readings for some dates, missing values for one building during a meter fault, and inconsistent building names.

Each issue is handled and justified: duplicates removed after confirming they were identical, missing values left blank and the affected period noted rather than filled with zero, and names standardised with a mapping table. Observations are clear and accurate, such as "median monthly use is lower than the mean because two large buildings use far more energy than the rest" and "usage peaks every winter". Strong answers note any limitations that affect the observations.

Key takeaways

  • Data wrangling turns raw data into a reliable, analysable form and often takes the largest share of project time.
  • Tidy data, with one variable per column and one observation per row, makes analysis much easier.
  • Joins are a common source of silent errors, so row counts should be checked before and after combining data.
  • Missing values and outliers need investigation and documented, proportionate decisions rather than automatic deletion or filling with zero.
  • Exploratory analysis combines summary statistics and charts; the median and interquartile range are more robust than the mean and range for skewed data.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 1 Unit 3 →
WhatsApp