Sub topic 6
Filling with constants and statistics
This chapter assumes you can create and index a pandas Series and DataFrame, and that you know how to find missing values with isna. Here you replace missing values with fillna, using either a constant or a statistic computed from the data.
What fillna does
fillna returns a new object in which missing values are replaced. The original is unchanged unless you assign the result back. You can pass a scalar, a dict keyed by column, or a Series.
Filling keeps every row, unlike dropna. The cost is that you now have invented values mixed with observed ones. Pick the replacement deliberately.
Filling a column with a statistic
For a numeric column, the mean or median is a common choice. The median is less affected by outliers. For a text column, a constant label such as "unknown" makes the gap visible.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
df["age"] = df["age"].fillna(df["age"].median())
df["city"] = df["city"].fillna("unknown")
print(df)The median of the two known ages (25 and 31) is 28.0, so both gaps in age become 28.0. The missing city becomes unknown.
Assign the result back to the column, as shown. Avoid inplace=True. It does not save memory in most cases, and chained forms such as df["age"].fillna(0, inplace=True) may act on a temporary copy and leave df unchanged.
Filling several columns at once
Pass a dict to give each column its own replacement. Columns not named in the dict are left alone.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
filled = df.fillna({"age": df["age"].mean(), "city": "unknown"})
print(filled)This is easier to read and review than one assignment per column. It also records your choices in a single place.
Choosing between mean, median and a constant
| Replacement | Good when | Watch out for |
|---|---|---|
| Mean | Values are roughly symmetric | Outliers pull it away from typical values |
| Median | Values are skewed or have outliers | Still shrinks the spread of the data |
| Mode (most common value) | The column is categorical | Over-represents the most common category |
| Constant such as 0 or `"unknown"` | The constant has a real meaning | A fake 0 distorts later averages |
Every statistic-based fill reduces the variance of the column, because many rows now share the same value. Correlations with other columns also weaken. For exploration this is usually acceptable. For modelling, consider whether the loss matters.
For a categorical column, mode() returns a Series, so take its first element:
import pandas as pd
cities = pd.Series(["Oslo", "Oslo", None, "Rome"])
cities = cities.fillna(cities.mode()[0])
print(cities)Common errors
- Filling before splitting data for a model. Computing the mean on the full dataset leaks information from the test rows into the training rows. Calculate the statistic on the training set only.
- Using 0 for missing numbers. A zero is a real measurement. It lowers means and hides the fact that the value was unknown. Use it only when "missing" truly means "none".
- Forgetting that fill values can change the dtype. Filling an integer-like float column leaves floats. Filling a numeric column with a string turns it into
object. - Not assigning the result.
df["age"].fillna(0)on its own prints a result but changes nothing.
A flow to follow
Exercise
A Series is s = pd.Series([4.0, np.nan, 100.0, 6.0, np.nan]). Would you fill it with the mean or the median, and what value does your choice produce for the gaps?
Show answer
Use the median, because 100.0 is an outlier. The known values are 4, 6 and 100, so the median is 6.0 and s.fillna(s.median()) fills both gaps with 6.0. The mean would be about 36.7, which is far from most of the data.
Exercise
Why does df["age"].fillna(0) on its own line leave df unchanged, and how do you fix it?
Show answer
fillna returns a new Series and does not modify the original. Assign the result back: df["age"] = df["age"].fillna(0).