Home Topics Data Preprocessing

Data Preprocessing

Clean, transform, and prepare your data

5 hours 20 examples Beginner
Basics

Why is Preprocessing Important?

Data preprocessing is often 80% of a data scientist's job! Raw data is messy - it has missing values, inconsistent formats, and features on different scales. ML models need clean, structured data to work correctly.

Garbage In = Garbage Out

If you feed a model bad data, it will produce bad predictions. No amount of algorithm tuning can fix poor data quality!

🔍 Missing Values

NaN, null, empty cells that break algorithms

📊 Different Scales

Age (0-100) vs Salary (0-1M) - need normalization

🏷️ Text Categories

"Red", "Blue", "Green" → must convert to numbers

🚨 Outliers

Extreme values that skew your model

Basics

Handling Missing Data

Missing data (NaN values) is the most common problem. You have 3 main options: remove, fill, or impute.

missing_data.py
import pandas as pd
import numpy as np

# Sample data with missing values
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'Age': [25, np.nan, 35, 28],
    'Salary': [50000, 60000, np.nan, 55000]
}
df = pd.DataFrame(data)

print("Original DataFrame:")
print(df)
print(f"\nMissing values per column:\n{df.isnull().sum()}")

# Option 1: Drop rows with any missing values
df_dropped = df.dropna()
print(f"\nAfter dropna(): {len(df_dropped)} rows")

# Option 2: Fill with a specific value
df_filled = df.fillna({'Age': df['Age'].mean(), 'Salary': 0})
print("\nAfter fillna (mean for Age, 0 for Salary):")
print(df_filled)
Output
Original DataFrame:
      Name   Age   Salary
0    Alice  25.0  50000.0
1      Bob   NaN  60000.0
2  Charlie  35.0      NaN
3    Diana  28.0  55000.0

Missing values per column:
Name      0
Age       1
Salary    1
dtype: int64

After dropna(): 2 rows

After fillna (mean for Age, 0 for Salary):
      Name   Age   Salary
0    Alice  25.0  50000.0
1      Bob  29.3  60000.0
2  Charlie  35.0      0.0
3    Diana  28.0  55000.0

When to Use Each Strategy

  • • dropna() - When <5% of data is missing
  • • fillna(mean) - For numerical columns with few outliers
  • • fillna(median) - When data has outliers
  • • fillna(mode) - For categorical columns
Transformations

Feature Scaling

Features on different scales (like age 0-100 vs salary 0-100,000) can cause problems. Scaling brings all features to a similar range.

StandardScaler (Z-score)

(x - mean) / std

Mean = 0, Std = 1. Best for most algorithms.

MinMaxScaler

(x - min) / (max - min)

Range 0 to 1. Good for images/neural networks.

feature_scaling.py
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import numpy as np

# Sample data with different scales
data = np.array([[25, 50000],
                 [30, 60000],
                 [35, 70000],
                 [40, 80000]])

print("Original data:")
print(f"Age range: {data[:,0].min()} - {data[:,0].max()}")
print(f"Salary range: {data[:,1].min()} - {data[:,1].max()}")

# StandardScaler
scaler_std = StandardScaler()
data_std = scaler_std.fit_transform(data)
print("\nAfter StandardScaler:")
print(np.round(data_std, 2))

# MinMaxScaler
scaler_mm = MinMaxScaler()
data_mm = scaler_mm.fit_transform(data)
print("\nAfter MinMaxScaler:")
print(np.round(data_mm, 2))
Output
Original data:
Age range: 25 - 40
Salary range: 50000 - 80000

After StandardScaler:
[[-1.34 -1.34]
 [-0.45 -0.45]
 [ 0.45  0.45]
 [ 1.34  1.34]]

After MinMaxScaler:
[[0.   0.  ]
 [0.33 0.33]
 [0.67 0.67]
 [1.   1.  ]]
Transformations

Encoding Categorical Data

ML algorithms only understand numbers! You must convert text categories like "Red", "Green", "Blue" to numerical values.

encoding.py
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder

# Sample categorical data
df = pd.DataFrame({
    'Color': ['Red', 'Blue', 'Green', 'Red', 'Blue'],
    'Size': ['S', 'M', 'L', 'M', 'S']
})
print("Original:")
print(df)

# Method 1: Label Encoding (0, 1, 2...)
le = LabelEncoder()
df['Color_Encoded'] = le.fit_transform(df['Color'])
print("\nLabel Encoding:")
print(df[['Color', 'Color_Encoded']])

# Method 2: One-Hot Encoding (dummy variables)
df_onehot = pd.get_dummies(df['Color'], prefix='Color')
print("\nOne-Hot Encoding:")
print(df_onehot)
Output
Original:
   Color Size
0    Red    S
1   Blue    M
2  Green    L
3    Red    M
4   Blue    S

Label Encoding:
   Color  Color_Encoded
0    Red              2
1   Blue              0
2  Green              1
3    Red              2
4   Blue              0

One-Hot Encoding:
   Color_Blue  Color_Green  Color_Red
0       False        False       True
1        True        False      False
2       False         True      False
3       False        False       True
4        True        False      False

When to Use Each

  • • Label Encoding - Ordinal data (S < M < L)
  • • One-Hot Encoding - Nominal data (Red ≠ Blue ≠ Green, no order)
Advanced

Complete Preprocessing Pipeline

Combine all steps into a reusable Pipeline. This ensures the same transformations are applied to both training and test data!

full_pipeline.py
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import numpy as np

# Create a preprocessing + model pipeline
pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='mean')),  # Step 1: Fill missing
    ('scaler', StandardScaler()),                  # Step 2: Scale
    ('classifier', LogisticRegression())           # Step 3: Model
])

# Sample data with missing values
X_train = np.array([[25, 50000], [np.nan, 60000], [35, 70000]])
y_train = np.array([0, 1, 1])

# Fit entire pipeline in one step!
pipeline.fit(X_train, y_train)

# Predict on new data (automatically preprocessed)
X_new = np.array([[28, 55000]])
prediction = pipeline.predict(X_new)

print(f"Prediction: {prediction[0]}")
print("✓ Missing values handled automatically!")
print("✓ Scaling applied automatically!")
Output
Prediction: 1
✓ Missing values handled automatically!
✓ Scaling applied automatically!

🎉 You've Mastered Data Preprocessing!

Learn how to evaluate your model's performance next.