By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Missing data is the silent killer of data pipelines. You pull a CSV from an API, load it into a DataFrame, and suddenly your model throws ValueError: Input contains NaN, infinity or a value too large for dtype('float32'). Or worse—your model trains fine, but predictions are garbage because missing values were silently imputed with zeros.
ValueError: Input contains NaN, infinity or a value too large for dtype('float32')
Real-world scenario:You’re building a customer churn prediction model. Your dataset has 10% missing values in the tenure column (how long a customer has been subscribed). If you drop all rows with missing values, you lose 10% of your data—and likely bias your model (e.g., newer customers might be underrepresented). If you fill missing values with the mean, you might artificially inflate retention rates. If you ignore them, your model crashes.
tenure
Why this matters in production:- Broken pipelines: Missing data can cause pandas operations to fail (e.g., groupby, merge, apply).- Biased models: Imputing missing values incorrectly can skew predictions (e.g., filling NaN with 0 in a salary column).- Regulatory risks: In healthcare or finance, missing data can violate compliance (e.g., GDPR requires explaining why data is missing).- Costly errors: A model deployed with unhandled missing data might make bad decisions (e.g., approving loans for customers with missing credit scores).
pandas
groupby
merge
apply
NaN
0
Superpower this gives you:You’ll be able to clean data efficiently, debug pipelines faster, and build more robust models—without losing sleep over NaN errors.
numpy
None
df.isna()
df.fillna(0)
isna()
isnull()
True
False
python df.isna().sum() # Count missing values per column
notna()
notnull()
python df[df['column'].notna()] # Keep rows where 'column' is not missing
dropna()
axis=0
axis=1
how='any'
how='all'
thresh=N
N
df.dropna()
thresh
df.dropna(thresh=5)
fillna()
value
"missing"
{'column1': 0, 'column2': 'unknown'}
method
'ffill'
'bfill'
axis
fillna(0)
age
temperature
interpolate()
method='linear'
'time'
'polynomial'
limit
python df['temperature'].interpolate(method='time') # Fill gaps in time-series
SimpleImputer
Pipeline
python from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy='median') df[['column']] = imputer.fit_transform(df[['column']])
python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) imputer = SimpleImputer(strategy='median').fit(X_train) X_train = imputer.transform(X_train) X_test = imputer.transform(X_test) # Use same imputer, don't refit!
scikit-learn
Clean the Titanic dataset for a survival prediction model. Handle missing values in: - Age (177 missing values) - Embarked (2 missing values) - Cabin (687 missing values)
Age
Embarked
Cabin
import pandas as pd import numpy as np # Load data df = pd.read_csv('titanic.csv') print(df.isna().sum()) # Audit missing values
Output:
PassengerId 0 Survived 0 Pclass 0 Name 0 Sex 0 Age 177 SibSp 0 Parch 0 Ticket 0 Fare 0 Cabin 687 Embarked 2 dtype: int64
PassengerId
Name
Ticket
df = df.drop(['Cabin', 'PassengerId', 'Name', 'Ticket'], axis=1)
Pclass
Sex
# Calculate median age by Pclass and Sex median_age = df.groupby(['Pclass', 'Sex'])['Age'].median() print(median_age)
Pclass Sex 1 female 35.0 male 40.0 2 female 28.0 male 30.0 3 female 21.5 male 25.0 Name: Age, dtype: float64
# Impute missing Age values df['Age'] = df.groupby(['Pclass', 'Sex'])['Age'].apply(lambda x: x.fillna(x.median())) print(df['Age'].isna().sum()) # Should be 0
S
df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode()[0]) print(df['Embarked'].isna().sum()) # Should be 0
print(df.isna().sum())
Survived 0 Pclass 0 Sex 0 Age 0 SibSp 0 Parch 0 Fare 0 Embarked 0 dtype: int64
df.to_csv('titanic_cleaned.csv', index=False)
README
"unknown"
% missing
prometheus
datadog
Age=0
Income
Gender
df[df['Income'].isna()]['Gender'].value_counts()
mean
median
df.isna().sum()
❌ df.isnull().count() (counts non-missing values)
df.isnull().count()
"How would you drop rows where Age is missing?"
df.dropna(subset=['Age'])
❌ df.dropna(axis=1) (drops columns, not rows)
df.dropna(axis=1)
"What’s the difference between fillna(0) and fillna(method='ffill')?"
fillna(method='ffill')
fillna(method='ffill'): Forward-fills NaN with the previous non-missing value.
"How do you avoid data leakage when imputing missing values?"
df.fillna(0).fillna(1)
1
"You have a dataset with 10% missing values in Income. The distribution is right-skewed. How would you impute missing values?"- ✅ Use median (robust to outliers).- ❌ Use mean (skewed by high earners).- ❌ Use 0 (biases the distribution).
Challenge:You have a DataFrame df with missing values in column1 and column2. Write a function that: 1. Drops rows where both column1 and column2 are missing.2. Fills remaining missing values in column1 with the median.3. Fills remaining missing values in column2 with "unknown".
df
column1
column2
Solution:
def clean_missing_data(df): # Drop rows where both columns are missing df = df.dropna(subset=['column1', 'column2'], how='all') # Fill column1 with median df['column1'] = df['column1'].fillna(df['column1'].median()) # Fill column2 with "unknown" df['column2'] = df['column2'].fillna("unknown") return df
Why it works:- how='all' ensures we only drop rows where both columns are missing.- fillna() with median/"unknown" handles the remaining missing values.
df.dropna(subset=['col'])
col
df.fillna(method='ffill')
df.interpolate()
SimpleImputer(strategy='median')
df.notna()
df.dropna(thresh=3)
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.