Skip to content
LearnPY
pandasfunction reference

DataFrame.fillna

Replace missing values with a constant or computed value.

Signature

DataFrame.fillna(value=None, *, method=None, axis=None, inplace=False)

What it does

fillna returns a copy with missing values replaced. Prefer fitting the replacement value on training data, especially when the value is a mean or median, so the test set does not influence preprocessing.

Parameters

valuescalar, dict, Series, or DataFrame
Replacement value or per-column mapping.
methodstr, optionaloptional
Fill forward or backward instead of using a value.
inplacebool, optionaloptional
Mutate the DataFrame instead of returning a copy.

Returns

DataFrame or None

Example

pythonDataFrame.fillna example
import pandas as pd
import numpy as np

df = pd.DataFrame({"score": [10.0, np.nan, 14.0]})
print(df.fillna({"score": df["score"].mean()}))

Output

   score
0   10.0
1   12.0
2   14.0

Watch out for

  • Computing the fill value on all rows leaks test information into training.
  • A single constant can hide why a value was missing; consider a missing indicator.