Sub topic 6
Filling with constants and statistics
This chapter covers fillna with a fixed value or a summary statistic. It assumes you can build and index a Series and DataFrame, and that you can detect missing values with isna. Forward fill, interpolation and group-wise filling come in later chapters.
What fillna does
fillna returns a new object in which every missing cell (NaN, None, NaT or pd.NA) is replaced by a value you supply. The original is untouched unless you assign over it.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s.fillna(0))The value can be a scalar, a dict, or a Series. Which one you pick decides whether every column gets the same value or each column gets its own.
Filling with one constant
Passing a scalar to a whole DataFrame fills every column with it. That is rarely what you want.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
print(df.fillna(0))The city column now holds the integer 0 next to city names. Pandas does not complain, because an object column can hold any Python value. The result is a column of mixed types that breaks later string operations.
A constant is a good choice when it has a real meaning for that column:
0for a count where "not recorded" truly means none, such as the number of purchases."unknown"or"missing"for a text label.Falsefor a flag that defaults to off.
It is a poor choice when the zero would be read as a measurement, such as an age of 0 or a temperature of 0.
Different values for different columns
Pass a dict that maps column names to fill values. Columns not named in the dict are left alone.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
filled = df.fillna({"age": df["age"].median(), "city": "unknown"})
print(filled)The median of age is 28.0, so both missing ages become 28.0. The name column is unchanged.
You can also pass a Series whose index holds column labels. This is the compact way to fill every numeric column with its own mean:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [25, np.nan, 31, np.nan],
"score": [8.0, 7.5, np.nan, 9.0],
"city": ["Oslo", None, "Rome", "Lima"],
})
filled = df.fillna(df.mean(numeric_only=True))
print(filled)numeric_only=True keeps city out of the statistics. city still has its missing value, because the Series has no entry for it. If you leave numeric_only out, text columns raise an error in current pandas.
Choosing a statistic
The statistic you pick changes the data you analyse afterwards.
| Statistic | Suits | Watch out for |
|---|---|---|
| Mean | Roughly symmetric numeric data | Pulled by outliers |
| Median | Skewed data such as income or prices | Ignores the shape of the distribution |
| Mode | Categories and discrete codes | Can have ties, and the mode may be rare |
| A fixed value | Cases where the default has a real meaning | Can look like a real measurement |
The mode needs one extra step. Series.mode() returns a Series, because several values can tie. Take the first entry:
import pandas as pd
city = pd.Series(["Oslo", "Rome", "Oslo", None, "Lima"])
most_common = city.mode().iloc[0]
print(most_common)
print(city.fillna(most_common)).iloc[0] is safer than [0] because it selects by position whatever the index is. If the column is entirely missing, mode() is empty and .iloc[0] raises IndexError, so check for that case first.
What filling does to your statistics
Filling with the mean keeps the mean the same and shrinks the spread, since every filled value sits exactly at the center.
import numpy as np
import pandas as pd
s = pd.Series([2.0, np.nan, 4.0, np.nan, 6.0, 8.0])
filled = s.fillna(s.mean())
print(round(s.mean(), 2), round(s.std(), 2))
print(round(filled.mean(), 2), round(filled.std(), 2))The mean is 5.0 both times. The standard deviation drops from 2.58 to 2.0. The more values you fill, the stronger the effect. It also weakens correlations between columns. If you will compute variances, confidence intervals or correlations afterwards, a heavily mean-filled column understates the real uncertainty.
Keep a record of what you filled
Once you fill a cell, it looks like any other value. If the fact that it was missing could matter later, record it first:
import numpy as np
import pandas as pd
df = pd.DataFrame({"age": [25, np.nan, 31, np.nan]})
df["age_was_missing"] = df["age"].isna()
df["age"] = df["age"].fillna(df["age"].median())
print(df)Create the indicator before you fill. After filling, isna finds nothing. The indicator column also lets a model, or a reviewer, tell real ages from imputed ones.
Assign the result, do not use inplace
fillna(..., inplace=True) is discouraged. It saves no memory in most cases and does not work reliably on a column selected from a DataFrame. Assign the result instead:
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)A pattern like df["age"].fillna(0, inplace=True) operates on an intermediate object. Depending on the pandas version, it either changes nothing in df or raises a warning. Assigning back with df["age"] = ... always works.
Limiting how many values get filled
The limit argument caps how many missing values are filled, counted from the top in each column:
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, np.nan, 4.0])
print(s.fillna(0, limit=1))Only the first NaN becomes 0. The second stays missing. limit matters more with forward fill, but it works here too.
Dtype effects
Filling can change or preserve the column dtype, and you should check which.
- A float column filled with a number stays
float64. An integer column cannot holdNaN, so a column with missing values is alreadyfloat64before you fill it. After filling, you can convert back withastype("int64")if the values are whole numbers. - A nullable column such as
Int64staysInt64after filling, and the fill value must fit the type. - A categorical column accepts only fill values that are already categories. Add the category first.
import pandas as pd
n = pd.Series([1, None, 3], dtype="Int64")
print(n.fillna(0).dtype)
c = pd.Series(["a", None, "b"], dtype="category")
c = c.cat.add_categories("unknown").fillna("unknown")
print(c)Calling c.fillna("unknown") without adding the category first raises a TypeError.
Avoid leaking information from the test set
If you fill missing values as preparation for a predictive model, compute the statistic on the training data only, then reuse that number on new data. Computing it on the combined data lets information from the test rows influence the training rows.
import numpy as np
import pandas as pd
train = pd.DataFrame({"age": [20.0, np.nan, 40.0]})
test = pd.DataFrame({"age": [np.nan, 50.0]})
median_age = train["age"].median()
train["age"] = train["age"].fillna(median_age)
test["age"] = test["age"].fillna(median_age)
print(test)Both sets use 30.0. Store the number, or the whole mapping of statistics, so you can apply the same fill in production.
Deciding which fill to use
Common errors
- Filling the whole DataFrame with one number. It writes
0into text columns. Use a dict. - Forgetting to assign.
df["age"].fillna(0)returns a new Series and discards it. Writedf["age"] = .... - Computing the statistic after a partial fill. Compute it from the original column, or the filled values will bias it.
- Using a sentinel that looks real. Filling with
-1or0is hard to tell apart from genuine data. If you must, document it, or keep the indicator column. - Ignoring all-missing columns. The mean and median of an all-missing column are
NaN, sofillnafills nothing.
Exercise
A DataFrame has a numeric column "price" with a few large outliers and some missing values, and a text column "brand" with some missing values. Write the line that fills "price" with the right statistic and "brand" with a label, in one call, without modifying the original DataFrame. Why did you choose that statistic?
Show answer
filled = df.fillna({"price": df["price"].median(), "brand": "unknown"}). The median is used because outliers pull the mean toward them, while the median stays near typical values. The dict gives each column its own fill value, and fillna returns a new DataFrame, so df is unchanged.
Exercise
You run df["age"].fillna(df["age"].mean(), inplace=True) and later find the missing ages are still there. Give a fix, and name one thing to do before filling if you want to remember which rows were imputed.
Show answer
Assign the result back: df["age"] = df["age"].fillna(df["age"].mean()). The inplace=True call acted on an intermediate Series, not on df. To remember which rows were imputed, create a Boolean column first with df["age_was_missing"] = df["age"].isna(), before the fill.