Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Data wrangling

Data wrangling is the process of cleaning, transforming and preparing raw data into a form suitable for analysis and visualization.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Data wrangling (also called data munging) prepares raw data so analysis and visualisation tools (Python, Tableau, Spark) give correct results. Engineers use it before modeling, plotting, or reporting: remove errors, fill missing values, convert types, join tables and reshape data so that downstream analytics and visualisations are meaningful and fast.

Key ideas

  • Raw data: data as collected from sources (files, sensors, logs, databases) without cleaning.

  • Cleaning: operations that correct or remove incorrect, corrupted, or irrelevant portions of data. Typical operations: remove duplicates, fix types, trim whitespace, correct obvious errors.

  • Missing value: a data cell with no valid value (null, NaN, empty string). Common treatments: deletion (drop rows/columns), imputation (replace with statistic or model), or flagging (add indicator variable). Assumptions: deletion assumes missing completely at random (MCAR); imputation methods assume missing at random (MAR) or that the imputer model is correct.

  • Outlier: an observation that is numerically distant from most other observations. Two standard detection rules:

    • Z-score method: compute z = (x - μ)/σ; mark |z| > 3 (or other threshold) as outlier. Assumes data roughly Gaussian when using z-scores.
    • IQR rule: compute IQR = Q3 − Q1; mark values < Q1 − 1.5·IQR or > Q3 + 1.5·IQR as outliers. Assumes distribution may be skewed; robust to non-normality.
  • Type conversion: ensure each column has a correct data type (integer, float, string/object, datetime, categorical). Converting strings to datetimes allows time-based grouping; converting numerics stored as strings requires parsing (check thousands separators, decimal symbols).

  • Parsing: converting raw text fields into structured pieces (e.g., split "FullName" into "FirstName" and "LastName", parse address components). Define the parsing rules carefully and handle exceptions.

  • Deduplication: remove repeated records. Exact duplicate removal is trivial; fuzzy deduplication requires string similarity (edit distance) and domain rules.

  • Reshaping (wide vs long):

    • Wide format: multiple measurements are spread across columns (e.g., sales_2019, sales_2020). Best for human-readable tables.
    • Long format: one measurement column and one factor column (year, value). Best for plotting and grouped operations.
    • To convert: use melt/stack to go wide→long; use pivot/unstack to go long→wide.
    • Diagram to draw in an exam: draw a table with columns (id, sales_2019, sales_2020) labelled "Wide". Arrow to second table with columns (id, year, sales) labelled "Long". Show one id row expanding into two rows after melt.
  • Joins / merges: combining tables by keys. Draw a Venn diagram of two sets A and B (left and right table). Label regions for inner (A ∩ B), left (A), right (B), and outer (A ∪ B). Exact meanings:

    • Inner join: keep rows with keys present in both tables.
    • Left join: keep all rows from left table; bring matching rows from right, fill missing with null.
    • Right join: keep all rows from right table.
    • Outer (full) join: keep all rows from either table. Assumptions: keys are unique on at least one side or many-to-one relationships understood.
  • Aggregation and grouping: compute summaries (count, sum, mean) for groups defined by one or more keys. Steps: group by key(s), apply aggregation, reset index for table output.

  • Categorical encoding: convert strings to categorical variables for memory efficiency and for modeling (one-hot encoding, ordinal encoding). Assumptions: ordinal encoding implies an order.

  • Scaling / normalization: change numerical scale for modeling or plotting: min–max scaling or standard scaling (zero mean, unit variance). Use when model or algorithm is sensitive to scale.

  • Data lineage / provenance: track where each datum came from and the transformations applied. Important for reproducibility and debugging.

Formulas

z = (x − μ) / σ — z-score for a value x, where μ is sample mean (units of x), σ is sample standard deviation (units of x); use to detect outliers under approximate normality. IQR = Q3 − Q1 — interquartile range; Q1 is 25th percentile, Q3 is 75th percentile, units same as data. lower = Q1 − 1.5·IQR — lower outlier threshold. upper = Q3 + 1.5·IQR — upper outlier threshold. mean_impute = (Σ x_i) / n_obs — simple mean imputation for missing numeric values; x_i are observed values, n_obs is number of observed values. median_impute = median(x) — median imputation replaces missing with median of observed values; robust to outliers. df.drop_duplicates() — pandas syntax to remove duplicate rows. df.dropna(axis=0 or 1, how='any' or 'all') — pandas syntax to drop rows or columns with missing values. df.fillna(value) — pandas syntax to fill missing values with a constant or dict of column values. pd.to_datetime(df['col'], format=...) — pandas: convert column to datetime (specify format if known). pd.melt(df, id_vars=[...], value_vars=[...], var_name='...', value_name='...') — pandas: wide→long. df.pivot(index='...', columns='...', values='...') — pandas: long→wide. pd.merge(left, right, how='inner|left|right|outer', on='key') — pandas: join tables. df.groupby(['col']).agg({'x': 'sum', 'y': 'mean'}) — pandas: group and aggregate. pd.get_dummies(df['cat'], prefix='cat') — pandas: one-hot encode categorical column. (x − x_min) / (x_max − x_min) — min–max scaling to map value x to [0,1] (use training-set x_min and x_max to avoid leakage). (x − μ) / σ — standard scaling (same as z-score) to zero mean and unit variance.

Worked examples

Example 1 — Missing value imputation (mean for numeric, mode for categorical):

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'id': [1, 2, 3, 4],
    'age': [25, np.nan, 35, 40],
    'gender': ['M', 'F', None, 'M']
})

# Numeric mean imputation
mean_age = df['age'].mean()
df['age'] = df['age'].fillna(mean_age)

# Categorical mode imputation
mode_gender = df['gender'].mode()[0]
df['gender'] = df['gender'].fillna(mode_gender)

print(df)

Sample input: the code above. Exact output:

   id   age gender
0   1  25.0      M
1   2  33.333333333333336      F
2   3  35.0      M
3   4  40.0      M

Final answer: mean_age = 33.333..., categorical mode = 'M'.

Example 2 — Reshaping wide→long and long→wide:

import pandas as pd

df_wide = pd.DataFrame({
    'id': [1, 2],
    'sales_2019': [100, 150],
    'sales_2020': [110, 160]
})

# Wide to long
df_long = pd.melt(df_wide, id_vars=['id'], value_vars=['sales_2019', 'sales_2020'],
                  var_name='year', value_name='sales')
# Clean year column
df_long['year'] = df_long['year'].str.replace('sales_', '')

# Long to wide
df_wide_again = df_long.pivot(index='id', columns='year', values='sales').reset_index()

print('Long format:')
print(df_long)
print('\nWide again:')
print(df_wide_again)

Sample input: the code above. Exact output:

Long format:
   id  year  sales
0   1  2019    100
1   2  2019    150
2   1  2020    110
3   2  2020    160

Wide again:
year  id  2019  2020
0     1   100   110
1     2   150   160

Example 3 — Joins (inner, left, outer):

import pandas as pd

left = pd.DataFrame({'id': [1, 2, 3], 'left_val': ['A', 'B', 'C']})
right = pd.DataFrame({'id': [2, 3, 4], 'right_val': [10, 20, 30]})

print('Inner join:')
print(pd.merge(left, right, how='inner', on='id'))
print('\nLeft join:')
print(pd.merge(left, right, how='left', on='id'))
print('\nOuter join:')
print(pd.merge(left, right, how='outer', on='id'))

Sample input: the code above. Exact output:

Inner join:
   id left_val  right_val
0   2        B         10
1   3        C         20

Left join:
   id left_val  right_val
0   1        A        NaN
1   2        B       10.0
2   3        C       20.0

Outer join:
   id left_val  right_val
0   1        A        NaN
1   2        B       10.0
2   3        C       20.0
3   4      NaN       30.0

Common mistakes

  • Dropping missing values without checking if missingness is systematic (not MCAR). This can bias results.
  • Using mean imputation despite heavy skew or outliers — median is better for skewed data.
  • Confusing wide and long formats; writing code for pivot without resetting index and ending with an indexed (or MultiIndex) DataFrame.
  • Joining on non-unique keys causing unintended row multiplication; always check key uniqueness or be deliberate about many-to-many joins.
  • Not parsing dates correctly (wrong format) and then grouping by the wrong units (day vs month).
  • Not converting categorical strings to consistent case/whitespace; 'India', 'india', ' India ' become three categories.

For your exam

  • Short notes: list steps and trade-offs for imputation methods, explain assumptions of z-score vs IQR outlier detection.
  • Derivations / proofs: small derivations like showing z-score standardises mean to 0 and variance to 1 for a sample (show steps summing z-values). State assumptions: sample mean μ and σ used. Clarify which σ you use: if σ is computed with denominator n (population SD), then Var(z)=1 under that definition; if using unbiased sample SD with denominator n−1, then the sample variance of z equals 1.
  • Numericals: perform IQR outlier detection or compute mean imputation with carried units and rounding; show each arithmetic step and final value.
  • Programs: write short pandas code for dropna, fillna, melt/pivot and merge; include sample input and output. Make sure code is syntactically correct and imports pandas.
  • Diagrams: for joins draw a two-circle Venn diagram and label regions for inner/left/right/outer; for reshape draw a small table before and after melt/pivot.

Full-marks answers must state assumptions (e.g., MCAR, normality), show intermediate calculations, and if code is given, show exact printed output for the sample input.

Quick check

  1. What is the IQR and how is it used to detect outliers?
  2. Name two ways to treat missing categorical values.
  3. What pandas function converts a wide table to long format?

Answers: 1) IQR = Q3 − Q1; mark values < Q1 − 1.5·IQR or > Q3 + 1.5·IQR as outliers. 2) Drop rows/columns, mode imputation, constant fill, or add a missing-category flag. 3) pd.melt

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?