🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Handle Missing Values

A missing value is a blank cell in a table. The Titanic data has blanks in age, and this lesson shows three ways to deal with them.

Count the blanks first

isna() marks each blank cell. The sum counts the blanks in one column.

import seaborn as sns
df = sns.load_dataset("titanic")
print(df.shape)
print("Age blanks:", int(df["age"].isna().sum()))
print("Deck blanks:", int(df["deck"].isna().sum()))
print("Embarked blanks:", int(df["embarked"].isna().sum()))

Drop the rows with blanks

dropna() with subset drops only the rows where age is blank. The other rows stay.

import seaborn as sns
df = sns.load_dataset("titanic")
print("Rows before:", len(df))
kept = df.dropna(subset=["age"])
print("Rows after:", len(kept))

Fill age with the middle value

SimpleImputer learns the median age, then fills each blank with it. No blanks are left after the fill.

import numpy as np
import seaborn as sns
from sklearn.impute import SimpleImputer
df = sns.load_dataset("titanic")
imputer = SimpleImputer(strategy="median")
filled = imputer.fit_transform(df[["age"]])
print("Median age:", imputer.statistics_[0])
print("Blanks left:", int(np.isnan(filled).sum()))

Example

import numpy as np
import seaborn as sns
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

df = sns.load_dataset("titanic")
X = df[["age", "fare", "pclass"]]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Choice 1: drop every row with a blank.
train_dropped = X_train.dropna()
test_dropped = X_test.dropna()
model_drop = LogisticRegression(max_iter=1000, random_state=42)
model_drop.fit(train_dropped, y_train.loc[train_dropped.index])
drop_score = accuracy_score(y_test.loc[test_dropped.index], model_drop.predict(test_dropped))

# Choice 2: fill the blanks with the median age.
imputer = SimpleImputer(strategy="median")
X_train_filled = imputer.fit_transform(X_train)
X_test_filled = imputer.transform(X_test)
model_fill = LogisticRegression(max_iter=1000, random_state=42)
model_fill.fit(X_train_filled, y_train)
fill_score = accuracy_score(y_test, model_fill.predict(X_test_filled))

# Choice 3: fill the blanks and add a column that marks them.
imputer_mark = SimpleImputer(strategy="median", add_indicator=True)
X_train_marked = imputer_mark.fit_transform(X_train)
X_test_marked = imputer_mark.transform(X_test)
model_mark = LogisticRegression(max_iter=1000, random_state=42)
model_mark.fit(X_train_marked, y_train)
mark_score = accuracy_score(y_test, model_mark.predict(X_test_marked))

print("Rows after dropping blanks:", len(train_dropped), "train,", len(test_dropped), "test")
print("Drop score:", round(drop_score, 4))
print("Fill score:", round(fill_score, 4))
print("Fill + mark score:", round(mark_score, 4))
print("Marked columns:", X_train_marked.shape[1])

Key points

  • Missing value: a blank cell where a number or a word should be
  • Use dropna() to drop every row with a blank
  • Use SimpleImputer to fill blanks with one value
  • Use strategy="median" to fill numbers with the middle value
  • Use add_indicator=True to add a column that marks each filled blank
  • Dropping rows shrinks the data, so the score comes from fewer rows

In this example, the Titanic table is loaded first. The features are age, fare, and ticket class, and the target is survival. A fifth of the rows is held back for testing. Choice 1 drops every row with a blank, so it trains on 572 rows and tests on 142 rows. Choice 2 fills the blanks with the median age and keeps all 891 rows. Choice 3 fills the blanks too, and adds one extra column that marks the rows that were blank. The mark helps a little: the fill-plus-mark score beats the plain fill score. The three scores come from the same split, but the drop score tests on fewer rows, so it is not a clean win.

Note

Fill values must come from the training rows only, never from the whole table.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A column has 177 blanks out of 891 rows. What does dropna() do to those rows?