Skip to main content
All tracks
ML and Data Science Foundations

Data Cleaning and Exploratory Analysis

Real data is messy. Cleaning and exploring it usually takes most of the time in a project.

Typical problems​

ProblemTypical fix
Missing valuesDrop, or impute (mean, median, mode, model-based)
Duplicatesdrop_duplicates()
Wrong typesConvert (to_datetime, astype)
Inconsistent categoriesNormalise case, trim spaces, map synonyms
OutliersInvestigate; cap, transform or remove with care
import pandas as pd

df = pd.read_csv("sales.csv")

print(df.isna().sum()) # missing per column
df["price"] = df["price"].fillna(df["price"].median())
df = df.drop_duplicates()
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df["city"] = df["city"].str.strip().str.title()

Exploratory data analysis (EDA)​

Look before you model.

print(df.shape)
print(df.dtypes)
print(df.describe(include="all"))
print(df["city"].value_counts().head())
print(df.corr(numeric_only=True)) # relationships
import matplotlib.pyplot as plt

df["price"].hist(bins=30) # distribution
plt.show()

df.plot.scatter(x="area", y="price") # relationship
plt.show()

Feature engineering​

TechniqueExample
ScalingStandardise numeric features (StandardScaler)
EncodingOne-hot encode categories (get_dummies, OneHotEncoder)
Date featuresDay of week, month, is_weekend
Interactions / ratiosprice_per_sqft = price / area
BinningAge groups

Avoid data leakage​

Fit scalers, imputers and encoders only on the training split, then apply them to validation and test data. Using information from the test set during training gives falsely good results.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

model = make_pipeline(StandardScaler(), LogisticRegression())
# model.fit(X_train, y_train) learns the scaler from training data only
Finished reading?

Mark it complete to track your progress across the docs.

Questions and discussion

Stuck on something here, or found a clearer way to explain it? Start a thread.

All discussions
  • Ask a question or share what helped
  • React to useful answers
  • Sign in with GitHub to post

Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.