← Data analysis with Python

Filling gaps

Replace missing values with a sensible number, and know when not to.

Start this lesson

Instead of dropping rows, you can fill gaps with fillna. The right fill depends on what a blank means. If a blank in "donations" means nothing was given, fill with 0. If a blank temperature reading means the sensor failed, filling with the column mean (or median) keeps the row without pulling the average up or down much. Filling is a choice that changes your data, so do it on purpose and mention it when you report results.

import io
import pandas as pd

csv_text = """name,age,steps,sleep
Ana,34,8200,7.5
Bo,51,,6.0
Cy,28,10400,
Dee,45,6100,8.0
Eli,,7300,6.5
Fay,39,,7.0
"""
health = pd.read_csv(io.StringIO(csv_text))
health["sleep"] = health["sleep"].fillna(health["sleep"].mean())
health["steps"] = health["steps"].fillna(0)
print(health)

Cy’s missing sleep becomes the average of the others (7.0). Bo’s and Fay’s missing steps become 0. Notice that filling steps with 0 would drag the average steps down, which might not be fair: maybe they just did not wear the tracker!

fillna returns a new Series; assign it back to the column to keep the change.

df.fillna({"steps": 0, "sleep": 7}) fills different columns with different values in one call.