By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Data cleaning and preprocessing turn raw, messy tables into a tidy, model‑ready matrix. It covers handling missing values, converting categorical variables to numbers, scaling numeric features, and fixing class‑imbalance so that algorithms learn the true signal instead of artefacts. In a churn‑prediction project, for example, you might impute missing “last login” dates, one‑hot encode “subscription tier”, scale “monthly spend”, and rebalance the rare “churn = 1” class before feeding the data to a Gradient‑Boosted Tree.
{'low':0,'medium':1,'high':2}
class_weight='balanced'
train_test_split(..., stratify=y)
df = pd.read_csv(...)
df.info()
df.isnull().sum()
SimpleImputer(strategy='median')
IterativeImputer
OneHotEncoder(sparse=False)
OrdinalEncoder
target encoding
StandardScaler
MinMaxScaler
RobustScaler
stratify=y
SMOTE
RandomUnderSampler
np.bincount(y_resampled)
sklearn.pipeline.Pipeline
ColumnTransformer
preprocess = ColumnTransformer([ ('num', Pipeline([('impute', SimpleImputer(strategy='median')), ('scale', StandardScaler())]), num_cols), ('cat', Pipeline([('impute', SimpleImputer(strategy='most_frequent')), ('oh', OneHotEncoder(handle_unknown='ignore'))]), cat_cols) ]) model = Pipeline([ ('prep', preprocess), ('clf', RandomForestClassifier(class_weight='balanced')) ])
Mistake: Imputing after train/test split. Correction: Fit imputer on the training set only and transform both sets; otherwise you leak information from the test set.
Mistake: One‑hot encoding a high‑cardinality column (e.g., ZIP code) leading to thousands of sparse columns. Correction: Use target encoding or frequency encoding for such features, or drop them if they add little predictive power.
Mistake: Scaling before splitting, then applying the same scaler to the test set. Correction: Fit scalers on training data only; Pipeline guarantees this.
Pipeline
Mistake: Balancing classes with SMOTE on the whole dataset. Correction: Apply SMOTE only on the training fold; otherwise synthetic points can appear in the validation set, inflating performance.
Mistake: Assuming class_weight='balanced' works for all algorithms. Correction: Verify the estimator supports it (e.g., LogisticRegression, RandomForest, XGBClassifier); for others, manually compute sample weights.
LogisticRegression
RandomForest
XGBClassifier
Scenario: Your churn dataset has 2 % churners. After training a logistic regression you see an AUC of 0.78 but precision = 0.12. Answer: Use SMOTE or class weighting and evaluate with Precision‑Recall curve (more informative for rare positives).
Scenario: You accidentally applied StandardScaler to a categorical column encoded as integers. Answer: The model will treat the scaled integers as continuous, corrupting the signal; fix by excluding that column from scaling or using proper encoding.
Scenario: After imputing missing ages with the mean, you notice the model’s residuals are biased for older customers. Answer: Switch to median or KNN imputation (or add a “was_missing” indicator) to capture the distributional shift.
SimpleImputer(strategy='mean')
k_neighbors
category_encoders.TargetEncoder(cv=5)
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.