Pandas: Cleaning & Preprocessing
df = pd.read_csv("sales.csv")| city | sales | |
|---|---|---|
| 0 | Dhaka | 120.0 |
| 1 | Khulna | NaN |
| 2 | Dhaka | 80.0 |
| 3 | Sylhet | 60.0 |
Real data has gaps: NaN means a missing value.
1Level 1 · BasicsBasics
Real data is messy. Some values are missing, some rows appear twice, numbers arrive as text ("1,500", "n/a"), names are typed in five different ways, and one person's salary has three extra zeros. A machine learning model can't fix any of this. It learns from exactly what you give it, so garbage in means garbage out.
Data cleaning means fixing mistakes and gaps so the data is correct. Preprocessing means reshaping correct data into the form a model needs: only numbers, no gaps, and columns on similar scales. This lesson is a complete guide to both with pandas, plus a few tools from scikit-learn (the ML library you'll meet properly in a later lesson). Every technique has a runnable example that prints the data before and after.
These examples use pandas and scikit-learn. The first run downloads them into your browser, so give it a moment.
The cleaning checklist
- Look at the data:
df.head(),df.info(),df.isna().sum(). - Tidy column names, text and types.
- Remove duplicates.
- Handle missing values: drop or fill.
- Handle outliers: remove or cap.
- Create features and encode categories as numbers.
- Split into training and test sets, then scale using the training set only.
1. Finding missing values
pandas marks a missing value as NaN ("not a number"). None and np.nan in your data both count as missing.
| Code | Tells you |
|---|---|
df.isna() | a True/False table: True where a value is missing |
df.isna().sum() | how many values are missing in each column |
df.isna().mean() * 100 | the percentage missing in each column |
df.isna().sum().sum() | the total number of missing cells |
df[df.isna().any(axis=1)] | the rows that have at least one gap |
df.info() | the non-null count and type of every column |
Watch for hidden missing values too: "n/a", "-", "unknown", 0 or -1 standing in for "no data". pandas sees those as real values until you turn them into NaN.
2. Dropping missing values
dropna removes rows (or columns) with gaps. It's quick, but every dropped row is lost information, so check how many rows you lose.
| Code | Removes |
|---|---|
df.dropna() | every row with any missing value |
df.dropna(how="all") | only rows where every value is missing (blank rows) |
df.dropna(subset=["score"]) | rows missing a value in the listed columns only |
df.dropna(thresh=3) | rows with fewer than 3 real (non-missing) values |
df.dropna(axis=1) | columns with any missing value |
df.dropna(axis=1, thresh=3) | columns with fewer than 3 real values |
A column that is mostly empty (say 70% missing) is usually better dropped as a column than filled. Otherwise a plain dropna() would throw away almost every row because of it.
3. Filling missing values
Filling (also called imputation) replaces each gap with a sensible guess, so you keep the row.
- Constant:
df["bonus"].fillna(0)ordf["city"].fillna("Unknown"), when missing really means "none" or "not given". - Mean (average):
df["age"].fillna(df["age"].mean()). - Median (middle value):
df["income"].fillna(df["income"].median()). A few huge values pull the mean up but barely move the median. - Mode (most common value):
df["city"].fillna(df["city"].mode()[0]).mode()returns a Series because there can be ties, so[0]takes the first one. - Forward fill:
df["temp"].ffill()copies the last known value down. Backward fill:df["temp"].bfill()copies the next known value up. - Group-wise fill:
df["temp"].fillna(df.groupby("city")["temp"].transform("median"))fills each gap with the median of its own group.transformgives back one value per row, lined up with the original rows. - Interpolate:
df["temp"].interpolate()draws a straight line between the neighbours, so a gap between 30 and 34 becomes 32.
Which method should I use?
| Situation | Good choice |
|---|---|
| Only a few rows have gaps, and you have plenty of data | dropna() |
| A column is mostly empty | drop the column: dropna(axis=1, thresh=...) or drop(columns=...) |
| Missing really means zero or "none" | a constant: fillna(0), fillna("Unknown") |
| Numbers spread evenly, no extreme values | mean |
| Numbers with outliers or a long tail (income, prices) | median |
| Categories (city, gender, colour) | mode, or "Unknown" as its own category |
| Values in time order that stay the same until they change (stock, a price) | ffill(), then bfill() for a gap at the start |
| Values in time order that change smoothly (temperature) | interpolate() |
| Groups differ a lot (salary by job, temperature by city) | group-wise median or mean with transform |
Remember that dropna, fillna and most other methods return a new object. Assign the result back: df = df.dropna() or df["age"] = df["age"].fillna(...).
4. Removing duplicates
df.duplicated()marks each row that repeats an earlier row;df.duplicated().sum()counts them.df.drop_duplicates()removes rows that are identical in every column.df.drop_duplicates(subset=["id"], keep="last")treats rows with the same id as duplicates and keeps the last (newest) one.keep="first"is the default.
Clean the text first: "Dhaka" and " dhaka" look different to pandas, so those duplicates stay hidden until you tidy them.
5. Fixing data types
Each column has a type (dtype): int64 for whole numbers, float64 for decimals, object or str for text, datetime64 for dates, bool for True/False. Numbers stored as text can't be averaged, so fix them early.
df["roll"].astype(int)converts a clean column. It raises an error if even one value can't be converted.pd.to_numeric(df["marks"], errors="coerce")converts what it can and turns the rest ("absent","n/a") into NaN. "Coerce" means "force".pd.to_datetime(df["joined"], format="%Y-%m-%d", errors="coerce")turns text into real dates, so.dt.year,.dt.monthand.dt.day_name()work.df["passed"].map({"yes": True, "no": False})turns words into True/False.
6. Cleaning text
The .str accessor applies a string method to every value in a column at once:
.str.strip()removes spaces at both ends..str.lower(),.str.upper(),.str.title()fix capital letters, so "DHAKA", "dhaka" and "Dhaka" become one value..str.replace(",", "")removes or swaps characters; addregex=Trueto use a pattern, for example.str.replace(r"\s+", " ", regex=True)squeezes repeated spaces.df["city"].replace({"dhk": "dhaka", "ctg": "chattogram"})(without.str) swaps whole values, which is ideal for fixing known typos and short forms.
7. Renaming and dropping columns
df.rename(columns={"Student Name": "name"})renames chosen columns.df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")tidies every name at once:" Student Name "becomes"student_name".df.drop(columns=["notes", "id"])removes columns a model shouldn't use (free text, ID numbers).
8. Encoding categorical data
Models need numbers, so text categories must be encoded (turned into numbers). First decide which kind of category you have:
- Nominal: no natural order (city, colour, blood group).
- Ordinal: a real order (Small < Medium < Large, SSC < HSC < Bachelor).
Label encoding
Gives each category a number: Dhaka 0, Khulna 1, Sylhet 2. Three ways:
df["city"].map({"Dhaka": 0, "Khulna": 1, "Sylhet": 2}): you choose the numbers.df["city"].astype("category").cat.codes: pandas numbers the categories in alphabetical order.LabelEncoder().fit_transform(df["bought"])from scikit-learn, also alphabetical.le.classes_shows the order. It's meant for the target (the column you predict), such as yes/no.
The catch: numbers suggest an order. A model may think Sylhet (2) is "bigger" than Dhaka (0), which means nothing. Use label encoding for the target, for two-value columns, and for tree models, which cope with arbitrary numbers.
Ordinal encoding
For ordered categories, give the numbers in the real order. Alphabetical order is wrong here: it gives Large 0, Medium 1, Small 2.
df["size"].map({"Small": 0, "Medium": 1, "Large": 2})OrdinalEncoder(categories=[["Small", "Medium", "Large"]])from scikit-learn.categories=takes one list per column, in order.
One-hot encoding
Makes one new 0/1 column per category: city_Dhaka, city_Khulna, city_Sylhet. Each row has a 1 in exactly one of them. No fake order is created.
pd.get_dummies(df, columns=["city"], dtype=int)is the quick pandas way.drop_first=Truedrops the first new column, because it can be worked out from the others (all zeros means Dhaka). Linear models prefer this.OneHotEncoder(sparse_output=False, handle_unknown="ignore")from scikit-learn remembers the categories it saw duringfit, so new data gets exactly the same columns, and an unseen city becomes all zeros instead of an error. Use this for real models.
| Encoding | Use it for | Watch out |
|---|---|---|
Label (map, cat.codes, LabelEncoder) | the target; yes/no columns; tree models | invents an order for nominal data |
Ordinal (map, OrdinalEncoder) | categories with a real order | always give the order yourself |
One-hot (get_dummies, OneHotEncoder) | nominal features, especially for linear models, KNN and neural networks | many categories create many columns |
9. Outliers
An outlier is a value far away from the rest: a typo (age 250), a sensor glitch, or a rare but real case (a billionaire). Outliers drag the mean and can distort a model. Two common ways to find them:
The IQR method
Q1 is the 25th percentile (a quarter of values are below it), Q3 the 75th percentile, and the IQR (interquartile range) is Q3 - Q1, the width of the middle half of the data.
q1 = df["salary"].quantile(0.25) q3 = df["salary"].quantile(0.75) iqr = q3 - q1 lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr outliers = df[(df["salary"] < lower) | (df["salary"] > upper)] df_clean = df[df["salary"].between(lower, upper)]
This is the same rule a box plot uses to draw its dots. It works well for skewed data because quartiles aren't pulled by extreme values.
The z-score method
A z-score says how many standard deviations a value is from the mean: z = (x - mean) / std. The standard deviation (std) measures how spread out the values are. A value with |z| > 3 is unusually far out.
z = (df["orders"] - df["orders"].mean()) / df["orders"].std() df_clean = df[z.abs() <= 3]
Use it for roughly bell-shaped data with plenty of rows. In a tiny dataset no value can reach |z| = 3, so people use a cut-off of 2 or 2.5 there.
Capping instead of removing
Capping (also called clipping or winsorizing) keeps the row but pulls the extreme value back to a limit: df["salary"].clip(lower, upper). With percentiles: df["salary"].clip(df["salary"].quantile(0.05), df["salary"].quantile(0.95)). Prefer capping when you have little data or the outlier is real; remove the row when the value is clearly an error. Never remove outliers from the test set just to get a better score.
10. Feature scaling
Age goes from 18 to 60; income from 10,000 to 500,000. Models that measure distances (KNN, k-means) or use gradient descent (linear and logistic regression, neural networks) let the big column dominate. Scaling puts features on similar ranges. Tree models don't need it.
| Method | Formula | Result | scikit-learn |
|---|---|---|---|
| Min-max normalization | (x - min) / (max - min) | values between 0 and 1 | MinMaxScaler() |
| Standardization (z-score) | (x - mean) / std | mean 0, standard deviation 1 | StandardScaler() |
| Robust scaling | (x - median) / IQR | centred on 0, not bothered by outliers | RobustScaler() |
Use min-max when you need a fixed 0 to 1 range (pixel values, neural networks), standardization as the usual default, and robust scaling when the column has outliers you decided to keep. StandardScaler divides by the population std, which is df.std(ddof=0) in pandas.
Fit on the training data only
A scaler learns numbers (min and max, or mean and std) when you call fit. Learn them from the training set only, then use the same scaler to transform both sets:
scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) # learn + apply X_test_s = scaler.transform(X_test) # apply only
The test set stands in for future data you haven't seen. If the scaler learns from it, test information leaks into training and your score looks better than it really is. This is called data leakage. The same rule applies to imputers and encoders: compute the fill value from the training rows.
11. Log transform for skewed data
A column is right-skewed when most values are small and a few are huge (income, house prices, views). np.log1p(df["income"]) computes log(1 + x), which squeezes the huge values together and spreads out the small ones. df["income"].skew() measures the lopsidedness: near 0 is symmetric. To undo it, use np.expm1.
12. Binning with cut and qcut
Binning turns a number into a category (a "bin").
pd.cut(df["age"], bins=[0, 12, 19, 59, 120], labels=["child", "teen", "adult", "senior"])uses edges you choose. A bin includes its right edge, so 19 is a teen.pd.qcut(df["income"], q=4, labels=["low", "mid", "high", "top"])makes bins with about the same number of rows each (quartiles).
13. Creating new features
Feature engineering means building new, more useful columns from the ones you have. Some good ones:
- Ratios and totals:
df["total"] = df["price"] * df["qty"], BMI from weight and height. - Date parts:
df["date"].dt.month,.dt.day_name(), a weekend flag.dt.dayofweek >= 5. - Flags:
(df["total"] > 1000).astype(int). - Text facts:
df["review"].str.len(), or a word count. - Group facts: each row compared with its group average, using
transform("mean").
14. Quick analysis with groupby, sort and filter
Once the data is clean, summaries are short:
- Filter rows with a condition:
df[df["sales"] > 500],df[df["region"].isin(["Dhaka", "Sylhet"])]. - Sort:
df.sort_values("sales", ascending=False).head(3)gives the top 3. - Group:
df.groupby("region")["sales"].agg(["sum", "mean", "count"])splits the rows into groups, summarises each one, and combines the answers, like a pivot table in Excel.
The intermediate stage goes further with named aggregation, joins, pivot tables and dates.
15. The whole pipeline
The last example takes a messy table all the way to a model-ready one, in this order: tidy names and text, fix types, drop duplicates, fill gaps, cap outliers, create features, encode, split, then scale with a scaler fitted on the training rows. The order matters: clean text before looking for duplicates, and split before learning anything (fill values, scaling) that the test set shouldn't influence. In a real project you'd learn the fill values from the training rows too; the advanced stage shows how scikit-learn pipelines do that for you.
Key points: find gaps withisna().sum(), then drop (dropnawithhow,subset,thresh,axis) or fill (constant, mean, median, mode, ffill/bfill, group-wise, interpolate); remove duplicates after cleaning text; fix types withto_numeric(errors="coerce")andto_datetime; label-encode targets, ordinal-encode ordered categories, one-hot encode the rest; find outliers with IQR or z-scores, then remove or cap them; scale with min-max, standard or robust scaling, fitted on the training data only; assign every result back.
See it in actiongroupby: split, add up, combine
Rows are grouped by region and each group's amounts are summed.
Try it yourselfExample 1: Finding missing values
None and np.nan both count as missing. We count the gaps per column, as a percentage, in total, and list the rows that have any.
Output appears hereFill the gaps
Fill the blanks so the missing marks are counted and then replaced with 0. The output is 2 then 150.0.
import pandas as pd s = pd.Series([50, None, 100, None]) print(s.().sum()) print(s.(0).sum())
Example 2: Every way to use dropna
The phone column is almost empty, so a plain dropna() deletes every row. Compare how="all", subset=, thresh= and axis=1, and count the rows each one keeps.
Output appears hereDuplicates not removed
This should remove the repeated row and print 2, but it still prints 3. Fix it.
Example 3: Fill with a constant, the mean, the median and the mode
One huge income pulls the mean far above the typical value, so the median is the safer fill. The mode fills the text column.
Output appears hereAverage per class
Fill the blanks so the program shows the average mark for class B: 85.0.
import pandas as pd df = pd.DataFrame({"cls": ["A", "B", "A", "B"], "mark": [70, 80, 60, 90]}) avg = df.("cls")["mark"].() print(avg["B"])
Count per city
Count how many students live in each city and print the count for Dhaka: 3.
Example 4: Forward fill, backward fill, group-wise fill and interpolate
A temperature log with gaps, including one at the very start. Each column shows a different fill. Notice that ffill can't fill the first gap, and the group-wise fill uses each city's own median.
Output appears hereJoin two tables
Merge students and marks on id, then print Tara's mark: 91.
Example 5: Finding and removing duplicates
duplicated() marks repeats. drop_duplicates() removes identical rows; subset= with keep="last" keeps only the newest row for each id.
Output appears hereExample 6: Fixing types: astype, to_numeric and to_datetime
Every column arrives as text. astype works on clean columns; to_numeric and to_datetime with errors="coerce" turn bad values into NaN or NaT ("not a time") instead of crashing.
Output appears hereExample 7: Cleaning text, renaming and dropping columns
Messy column names, extra spaces, mixed capitals, a short form (DHK) and four spellings of gender. After cleaning, the cities collapse to two values.
Output appears hereExample 8: Label encoding and ordinal encoding
City has no order, so any numbers are only labels. Size does have an order: cat.codes numbers it alphabetically (wrong), while map and OrdinalEncoder with categories= follow Small, Medium, Large.
Output appears hereExample 9: One-hot encoding with get_dummies and OneHotEncoder
get_dummies is quick; drop_first=True removes one redundant column. OneHotEncoder remembers the cities it was fitted on, so new data gets the same columns and an unseen city becomes all zeros.
Output appears hereExample 10: Outliers with the IQR method: detect and remove
Salaries in thousands of taka. One is a typo (5) and one is a director (120). The IQR fences flag both; removing them moves the mean much closer to the median.
Output appears hereExample 11: Outliers with z-scores, and capping instead of removing
Twenty days of orders with one festival spike. The z-score finds it; remove it, or keep the row and cap the value with clip, using the IQR fences or the 5th and 95th percentiles (winsorizing).
Output appears hereExample 12: Scaling by formula and with scikit-learn
Age and income on very different scales. The formulas give the same numbers as MinMaxScaler and StandardScaler. Because of the 250,000 outlier, min-max squeezes the normal incomes near 0, while RobustScaler keeps them spread out.
Output appears hereExample 13: Fit the scaler on the training data only
The scaler learns the mean and std from the 7 training rows, then the same numbers transform the 3 test rows. Fitting on all 10 rows would let the test rows leak into training.
Output appears hereExample 14: Log transform and binning with cut and qcut
Income is strongly right-skewed (skew above 2); log1p brings the skew below 1. cut uses age edges we choose; qcut splits income into four groups of equal size.
Output appears hereExample 15: Creating new features
From five plain columns we build a total, a unit-price ratio, date parts, a weekend flag, a big-order flag, a text length and a comparison with each customer's average.
Output appears hereExample 16: Quick analysis: filter, sort and groupby
Once the data is clean: filter rows with a condition, sort for a top 3, and summarise each region.
Output appears hereExample 17: A full cleaning pipeline: messy CSV to a model-ready table
A messy customer file with bad names, spaces, a duplicate, text numbers, gaps, an outlier and categories. Each step prints its effect; the result is all numbers, no gaps, scaled with the training rows only.
Output appears here2Level 2 · IntermediateAnalysing clean data: groupby, joins, reshaping and dates
Cleaning is only half the job. Once the data is tidy, these tools answer the real questions: which region sells most?, which orders have no customer?, how did sales change week by week?
groupby in depth
Named aggregation gives tidy column names: df.groupby("region").agg(total=("sales", "sum"), orders=("sales", "count"), best=("sales", "max")). Group by several columns with a list, df.groupby(["region", "product"]), and add .reset_index() to turn the result back into an ordinary table.
size()counts rows per group;count()counts non-missing values.transformreturns one value per row, so you can compare each row with its group:df["share"] = df["sales"] / df.groupby("region")["sales"].transform("sum").filterkeeps whole groups that pass a test:df.groupby("region").filter(lambda g: len(g) >= 3).
Joining tables
pd.merge(orders, customers, on="cid") joins two tables on a shared key column, like VLOOKUP in Excel. If the key has different names, use left_on="cid", right_on="customer_id".
how= | Keeps |
|---|---|
"inner" (default) | only keys found in both tables |
"left" | every row of the left table; missing matches become NaN |
"right" | every row of the right table |
"outer" | every key from either table |
indicator=True adds a _merge column saying where each row came from. validate="one_to_one" (or "many_to_one") raises an error if a key repeats when it shouldn't, so a join never silently duplicates rows. pd.concat([df1, df2], ignore_index=True) stacks tables with the same columns.
Reshaping: wide and long
A wide table has one column per month; a long table has one row per (item, month). df.melt(id_vars="item", var_name="month", value_name="sales") turns wide into long, and df.pivot(index="item", columns="month", values="sales") turns it back. pivot_table(..., aggfunc="sum", margins=True) summarises with totals, and pd.crosstab(df["class"], df["grade"]) counts how often each pair of categories appears.
Dates and time series
df[df["date"] >= "2026-04-01"]filters by date;(df["date"].max() - df["date"].min()).dayscounts the days between.df.set_index("date").resample("W")["sales"].sum()isgroupbyfor time:"D"daily,"W"weekly,"MS"monthly.s.rolling(3).mean()is a rolling average: the mean of each value and the two before it, which smooths out noise.s.shift(1)moves values down one row, sos - s.shift(1)is the change from the previous day, ands.pct_change()the change in percent.
See it in actiongroupby builds a summary
Watch the grouped summary table appear as a new DataFrame.
Example 18: Named aggregation, transform and filter
One summary row per region, each sale's share of its region's total, and only the regions with at least 3 sales.
Output appears hereExample 19: Joins of every kind, checked
Order 5 belongs to a customer who isn't in the customer table, and Tuhin has no orders. Each how= treats them differently; indicator=True shows where each row came from, and validate= catches a repeated key.
Output appears hereExample 20: Wide to long, pivot tables and crosstab
melt turns month columns into rows so you can group by month; pivot turns them back; margins=True adds totals. crosstab counts grades per class.
Output appears hereExample 21: Dates, resample, rolling and shift
Six weeks of daily sales. The dt accessor gives parts of each date; resample adds them up per week; rolling smooths them; shift and pct_change compare each day with the day before.
Output appears here3Level 3 · AdvancedPreprocessing pipelines with scikit-learn
In the main lesson we filled, encoded and scaled with pandas by hand. That works, but in a real project it's easy to make a mistake: compute a fill value from the whole dataset (leakage), forget a step when new data arrives, or end up with different one-hot columns for the test set. scikit-learn's pipelines solve all three.
Imputers
An imputer is a fill step that learns its fill values in fit and applies them in transform, just like a scaler.
SimpleImputer(strategy="mean"),"median","most_frequent"(the mode) or"constant"withfill_value=.add_indicator=Trueadds a 0/1 column saying "this value was missing", because sometimes the gap itself is informative.KNNImputer(n_neighbors=2)fills a gap with the average of the 2 most similar rows (its nearest neighbours), using the other columns to judge similarity.
ColumnTransformer and Pipeline
A Pipeline chains steps in order: Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]). A ColumnTransformer sends different columns to different pipelines (numbers to impute-and-scale, ordered categories to OrdinalEncoder, other categories to OneHotEncoder) and glues the results side by side.
Put the preprocessing and the model in one pipeline. Then pipe.fit(X_train, y_train) learns every fill value, category list and scaling number from the training rows only, and pipe.predict(new_rows) repeats exactly the same steps on raw, messy new data.
Custom steps
FunctionTransformer(np.log1p, feature_names_out="one-to-one") turns any function into a step, such as a log transform for a skewed column.
Cross-validation without leakage
cross_val_score(pipe, X, y, cv=5) splits the data 5 ways and trains 5 times. Because the scaler sits inside the pipeline, it's refitted on each training part, so the held-out part never leaks in.
Example 22: SimpleImputer, add_indicator and KNNImputer
The imputer learns the median and the most frequent city from the training rows, then fills the test rows with those same values. KNNImputer fills each gap from the two most similar rows.
Output appears hereExample 23: One pipeline from messy rows to predictions
A ColumnTransformer imputes, log-transforms and scales the numbers, ordinal-encodes education and one-hot encodes city. The whole pipeline is fitted on the training rows, then predicts brand-new rows with gaps and a city it has never seen.
Output appears hereExample 24: Cross-validation with the scaler inside the pipeline
Five train-and-test rounds on the breast cancer dataset. The scaler is refitted inside every round, so no round ever learns from its own test part.
Output appears heredf.dropna() or df["age"].fillna(0) on its own line doesn't change df. It returns a cleaned copy. Write df = df.dropna() and df["age"] = df["age"].fillna(0). A second classic mistake is fitting a scaler or imputer on the whole dataset before splitting: fit on X_train, then only transform X_test.What does this print?
import pandas as pd s = pd.Series([4, None, 10, None]) print(s.fillna(s.mean()).sum())
50 graded problems are waiting in Topic Practice.