⚡0 XP🔥0

Data Preparation for Machine Learning

Lesson 2 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Load and explore data with pandas, handle missing values, encode categorical columns (one-hot, ordinal), scale features (StandardScaler, MinMaxScaler), split data correctly and avoid data leakage.

Data scientists often say that 80% of the work is preparing data. Models only learn well from clean, numeric, well-scaled data. This lesson covers the essential steps.

Look at the data first#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
(8, 6)
name            object
city            object
study_hours    float64
attendance     float64
level           object
passed           int64
dtype: object
name           0
city           1
study_hours    1
attendance     1
level          0
passed         0
dtype: int64
       study_hours  attendance  passed
count         7.00        7.00    8.00
mean          5.21       81.57    0.75
std           2.21       13.77    0.46
min           2.00       60.00    0.00
25%           3.75       73.00    0.75
50%           5.50       82.00    1.00
75%           6.75       93.00    1.00
max           8.00       97.00    1.00

shape, dtypes, isna().sum() and describe() are the first four things to run on any new dataset.

Handling missing values#

Options:

  1. Drop rows with missing values - fine when very few rows are affected.
  2. Drop a column - when most of it is missing.
  3. Impute (fill in) - mean or median for numbers, the most frequent value or "Unknown" for categories.
▶ Try it YourselfPython
Ctrl + Enter to run
Output
Rows if we drop: 5
   study_hours  attendance      city
0          4.5   82.000000    Bhopal
1          6.0   91.000000    Indore
2          5.5   76.000000    Indore
3          7.5   95.000000    Indore
4          2.0   60.000000  Jabalpur
5          5.5   81.571429    Indore
6          8.0   97.000000     Dewas
7          3.0   70.000000     Dewas

scikit-learn's SimpleImputer does the same and fits neatly into pipelines (see the tuning lesson).

हिंदी में समझें

Data में खाली जगहें (missing values) ज़्यादातर models स्वीकार नहीं करते। या तो वो rows हटा दें, या उन्हें भरें - numbers के लिए median/mean, और categories के लिए सबसे ज़्यादा आने वाली value या "Unknown"। Median बेहतर है क्योंकि बहुत बड़ी/छोटी values (outliers) उसे प्रभावित नहीं करतीं।

Encoding categorical data#

Models work with numbers, so text categories must be encoded.

One-hot encoding - one 0/1 column per category. Use it when categories have no order (cities, colours):

▶ Try it YourselfPython
Ctrl + Enter to run
Output
   marks  city_Bhopal  city_Dewas  city_Indore
0     70            1           0            0
1     88            0           0            1
2     64            0           0            1
3     91            0           1            0

Ordinal encoding - map ordered categories to ordered numbers (low < medium < high):

▶ Try it YourselfPython
Ctrl + Enter to run
Output
[1, 2, 0, 2, 1]
[1. 2. 0. 2. 1.]
Common Mistake

Do not give unordered categories numbers like Indore=1, Bhopal=2, Dewas=3 - the model would think Dewas is "bigger" than Indore. Use one-hot for those.

Feature scaling#

Features often have very different ranges: attendance 60-97, study hours 2-8, family income in lakhs. Distance-based models (KNN, K-means, SVM) and gradient-descent models (linear/logistic regression, neural networks) work much better when features are on similar scales.

Scaler Formula Result
StandardScaler (x - mean) / std mean 0, std 1
MinMaxScaler (x - min) / (max - min) range 0 to 1
RobustScaler (x - median) / IQR robust to outliers
▶ Try it YourselfPython
Ctrl + Enter to run
Output
Standardised:
 [[ 0.1  -0.28]
 [ 0.83  0.55]
 [-0.39  0.  ]
 [ 1.15  1.38]
 [-1.68 -1.65]]
Min-max:
 [[0.63 0.45]
 [0.89 0.73]
 [0.46 0.55]
 [1.   1.  ]
 [0.   0.  ]]

Tree-based models (decision trees, random forests) do not need scaling.

Splitting correctly and avoiding leakage#

Split first, then learn every preprocessing statistic (median, mean, std, categories) from the training set only, and apply it to both sets:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
train: (133, 13)  test: (45, 13)
class counts train: [44 53 36]  test: [15 18 12]
alcohol mean (train, scaled): 0.00
alcohol mean (test, scaled):  -0.11

The test set's scaled mean is close to, but not exactly, 0 - that is correct. It was scaled with the training statistics, exactly as future real-world data will be.

Tip

Common split sizes: 80/20 or 75/25 for train/test. For tuning, either split once more into train/validation/test, or use cross-validation on the training set.

Summary#

  • Explore with shape, dtypes, isna().sum(), describe().
  • Handle missing values by dropping or imputing (median for numbers, mode/"Unknown" for categories).
  • One-hot encode unordered categories; ordinal-encode ordered ones.
  • Scale features for distance and gradient-based models.
  • Split first, fit preprocessing on the training set only - no data leakage.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Fill missing values and one-hot encode

For the DataFrame in the starter: fill missing age with the median age, fill missing city with "Unknown", then one-hot encode city with pd.get_dummies(df, columns=["city"], dtype=int). Store the result in clean and print it.

2

Scale without leakage

Split X, y (wine data) with train_test_split(X, y, test_size=0.25, random_state=0). Fit a StandardScaler on the training set only, transform both sets into X_train_s and X_test_s, and print the mean of the first column of X_train_s rounded to 3 decimals (it should be 0.0).

Quick Quiz

Q1.

Why do most ML models need categorical text like "Indore" converted to numbers?

Q2.

What does StandardScaler do to a feature?

Q3.

When should you fit the scaler?

Q4.

A good simple strategy for missing numeric values is...