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 preprocessing in pandas

Practical, exam-focused notes on data preprocessing in pandas: reading data, handling missing values, duplicates, types, dates, encoding, scaling, merging and common pitfalls.

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 preprocessing prepares raw data so analyses and models work correctly. Engineers use preprocessing in pipelines (data wrangling, predictive analytics, and visualisation) to clean, normalise and join datasets before plotting or machine learning.

Key ideas

  • Missing value (NaN/NA) — a placeholder for missing data. In pandas, missing numeric entries become NaN (a special float), and missing object/string entries may be None, NaN, or the newer scalar pd.NA with nullable dtypes. Many preprocessing functions detect and treat missing values specially; use isna()/notna() to locate them.

  • Reading data — use read_csv, read_excel, read_json to load data into a DataFrame. Pandas infers dtypes from the parsed data (often in chunks when low_memory=True), which can yield mixed types; override with the dtype argument, converters, or set low_memory=False. You can also parse dates with parse_dates=[...].

  • Inspecting data — head(), tail(), shape, columns, dtypes, and info() show structure and types. Use isna().sum() to count missing values per column and describe() to summarize numerics. Always inspect dtypes before transformations.

  • Handling missing values — two main strategies: deletion and imputation. Deletion removes rows/columns with missing values (use dropna). Imputation fills missing values (use fillna) with a constant, mean/median, a forward/backward fill, or model-based estimates. State assumptions: deletion typically assumes data are missing completely at random (MCAR) or that losing rows doesn't bias results; mean imputation preserves the column mean but shrinks variance and can bias correlations—use only under strong MCAR/MAR assumptions and document time-order when using ffill/bfill.

  • Duplicates — use drop_duplicates to remove repeated rows. Decide whether duplicates are exact row duplicates or duplicates by a key column.

  • Data types and conversion — use astype() to convert types, to_numeric for safe numeric conversion, to_datetime for date conversion. Converting strings to datetime allows time-based indexing and resampling. Prefer pandas' nullable dtypes (Int64, string, boolean) when you need to allow missing values in integer/boolean/text columns.

  • Indexing and selection — .loc selects by label, .iloc by integer position. Setting a column as the index with set_index can make joins and resampling easier. Sorting: use sort_values([...]) to sort rows by columns and sort_index() to sort by index before time-based operations and merges.

  • Categorical data and encoding — categorical variables are stored as category dtype for efficiency. For many models, convert categories to numeric via one-hot encoding (get_dummies) or label encoding (mapping or .astype('category').cat.codes). One-hot increases columns; consider drop_first=True to avoid a redundant column. Label encoding assigns integer codes (NaN becomes -1) and may be treated as ordinal by models—use with care.

  • Merging and concatenation — use merge (SQL-like joins) to combine on key columns (how='left'|'right'|'inner'|'outer'). Use concat to stack DataFrames vertically or horizontally.

  • Scaling and normalization — pandas alone can do simple scaling via arithmetic; use sklearn scalers (StandardScaler, MinMaxScaler) for production pipelines. Scaling assumptions: many ML models expect features on similar scales.

  • Pipelines and reproducibility — record every transformation step in code and apply the same steps to train and test data. Fit imputers/scalers/encoders on the training set and reuse them to transform the test set to avoid leakage. Save dtypes, fill values, and encoders for reuse.

When an exam asks for a derivation or algorithm, show step-by-step code or pseudo-code that takes a raw table, identifies dtypes, handles missing values, encodes categoricals, scales numeric columns, and merges related tables.

Formulas

List of pandas syntax to remember (each line is a separate command or expression):

import pandas as pd — import pandas library.

df = pd.read_csv('file.csv') — read CSV into DataFrame.

df.head(n) — first n rows; df.tail(n) — last n rows.

df.shape — (rows, columns); df.columns — column labels; df.dtypes — column types.

df.dropna(axis=0, how='any', subset=[...], inplace=False) — drop rows (axis=0) or columns (axis=1) with NaN; how is 'any' or 'all'.

df.fillna(value, method=None, inplace=False) — fill NaN with a value or method ('ffill'/'bfill').

df.drop_duplicates(subset=[...], keep='first', inplace=False) — remove duplicate rows.

df['col'] = df['col'].astype('Int64') — change dtype of a column (use nullable Int64 to allow NA).

pd.to_datetime(df['date_col'], errors='coerce') — convert to datetime; invalid parses become NaT; use format='...' or dayfirst=True if needed.

df.set_index('id', inplace=False) — set a column as index.

df.merge(df2, how='left', on='key') — SQL-style join on a key.

pd.get_dummies(df['cat_col'], prefix='cat') — one-hot encode a categorical column.

df.groupby('key').agg({'val':'mean'}) — group and aggregate.

pd.concat([df1, df2], axis=0) — stack DataFrames vertically; axis=1 for columns.

df.sample(frac=0.1, random_state=1) — random sample of rows.

Note: inplace=True modifies the DataFrame and returns None; it's often discouraged in pipelines because it breaks method chaining and can be slower or confusing.

Worked examples

Example 1 — reading, inspecting, removing duplicates and viewing dtypes (complete program):

import pandas as pd
from io import StringIO
csv = """name,age,city,salary
Alice,30,Bengaluru,70000
Bob,,Chennai,60000
Charlie,25,,50000
Alice,30,Bengaluru,70000
"""

df = pd.read_csv(StringIO(csv))
print('Original DataFrame:')
print(df)
print('\nDtypes:')
print(df.dtypes)

# Remove exact duplicates
df_nodup = df.drop_duplicates()
print('\nAfter drop_duplicates():')
print(df_nodup)

Sample input: (the CSV string above) Exact output:

Original DataFrame: name age city salary 0 Alice 30.0 Bengaluru 70000 1 Bob NaN Chennai 60000 2 Charlie 25.0 NaN 50000 3 Alice 30.0 Bengaluru 70000

Dtypes: name object age float64 city object salary int64 dtype: object

After drop_duplicates(): name age city salary 0 Alice 30.0 Bengaluru 70000 1 Bob NaN Chennai 60000 2 Charlie 25.0 NaN 50000

Example 2 — imputation and type conversion:

import pandas as pd
from io import StringIO
csv = """id,score,date
1,85,2020-01-10
2,,2020-01-12
3,78,not_a_date
"""

df = pd.read_csv(StringIO(csv))
# Convert score to numeric (no change) and date to datetime
df['score'] = pd.to_numeric(df['score'], errors='coerce')
df['date'] = pd.to_datetime(df['date'], errors='coerce')
# Impute missing numeric with mean
mean_score = df['score'].mean()
df['score'] = df['score'].fillna(mean_score)
print(df)
print('\nMean used for imputation:', mean_score)

Exact output:

id score date 0 1 85.0 2020-01-10 1 2 81.5 2020-01-12 2 3 78.0 NaT

Mean used for imputation: 81.5

(Explanation: mean of [85, 78] is 81.5)

Example 3 — categorical encoding and merge:

import pandas as pd
from io import StringIO
left_csv = """id,product,price
1,pen,10
2,pencil,5
3,eraser,8
"""
right_csv = """product,brand
pen,BrandA
pencil,BrandB
notebook,BrandC
"""
left = pd.read_csv(StringIO(left_csv))
right = pd.read_csv(StringIO(right_csv))
# One-hot encode product in left (not typical before merge but shown for exam)
one_hot = pd.get_dummies(left['product'], prefix='prod')
merged = left.merge(right, how='left', on='product')
print('One-hot encoding:')
print(one_hot)
print('\nMerged table:')
print(merged)

Exact output:

One-hot encoding: prod_eraser prod_pen prod_pencil 0 0 1 0 1 0 0 1 2 1 0 0

Merged table: id product price brand 0 1 pen 10 BrandA 1 2 pencil 5 BrandB 2 3 eraser 8 NaN

Common mistakes

  • One-hot encoding high-cardinality categorical variables without reducing categories (creates very wide DataFrames and overfits models).
  • Using inplace=True and assuming functions return the modified DataFrame (they return None).
  • Converting dates with pd.to_datetime without errors='coerce' and then failing when parse errors occur.
  • Mixing index-based selection (iloc) and label-based (loc) incorrectly and causing off-by-one errors.

For your exam

Types of questions you will see:

  • Definitions: define DataFrame, Series, NaN, dtype, one-hot encoding.
  • Short notes: explain strategies for missing values; pros and cons of mean imputation; when to use one-hot vs label encoding.
  • Derivations/algorithms: write step-by-step code/pseudocode to clean a table: detect missing values, impute, convert types, encode categoricals, and save the pipeline.
  • Programs: small Python programs using pandas (like the worked examples). Full-marks answers show all imports, small sample data or StringIO, every intermediate print or comment explaining why a step is done.
  • Diagrams: draw a table before and after a transformation. For a join, draw two boxes labelled Table A and Table B, arrows showing join keys and the resulting table; label join type (left/inner/outer) and which rows appear.

To score full marks in code questions: show deterministic sample input, show intermediate inspection (dtypes, head()), apply transformations, and show final output with explanation of assumptions (e.g., why mean imputation is acceptable or why rows were dropped).

Quick check

  1. Which pandas method converts a column to datetime, and what parameter forces invalid parses to NaT?
  2. To remove rows that are exact duplicates across all columns which function do you use?
  3. What is the difference between get_dummies and .astype('category').cat.codes?

Answers: 1) pd.to_datetime(..., errors='coerce'); 2) df.drop_duplicates(); 3) get_dummies creates one-hot indicator columns (no ordinal order), cat.codes maps categories to integer codes (imposes numeric labels and implies an order), so use get_dummies for non-ordinal categories and cat.codes for ordinal or compact representation.

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

Stuck on something here?