Impute a common numeric default
A numeric feature has absent observations and downstream calculations require a defined fallback.
Pandas · Function
Replaces missing values in a DataFrame with a scalar or aligned, column-specific values. It returns a filled copy by default, or can modify the original in place.
Call fillna on a DataFrame with a scalar or aligned values to replace missing entries. By default it returns the filled DataFrame; use inplace=True to modify the existing object, and limit can cap how many missing entries are filled along an axis.
DataFrame.fillna(*value*, ***, *axis=None*, *inplace=False*, *limit=None*)| Name | Type | Description |
|---|---|---|
value | scalar, dict, Series, or DataFrame | Scalar, dictionary, Series, or DataFrame used to replace missing values; mappings or aligned objects can specify values by column. |
axis | {0 or 'index', 1 or 'columns'}, default None | Axis along which values are filled; DataFrames accept 0 or index, and 1 or columns. |
inplace | bool, default False | Whether to modify the DataFrame in place. |
limit | int, default None | Maximum number of entries along the entire axis to fill; must be positive when provided. |
DataFrame or None. A filled DataFrame is returned unless inplace=True, in which case the operation returns None.
import pandas as pd
df = pd.DataFrame({
"score": [10, None, 30],
"team": ["A", "B", None],
})
filled = df.fillna({"score": 0, "team": "unknown"})
print(filled)Fills each column's missing entries with a column-specific value.
A numeric feature has absent observations and downstream calculations require a defined fallback.
Different columns need semantically appropriate replacements, such as zero for counts and a label for categories.
A cleanup job must avoid filling more than a controlled number of missing cells.
It replaces missing values with the supplied value. The value may be a scalar or aligned mapping-like object such as a dictionary, Series, or DataFrame.
Follow-up: How would you fill different columns differently? Pass a dictionary whose keys are column names and whose values are the respective replacements.
With inplace=False, the operation returns a filled DataFrame and leaves the original unchanged. With inplace=True, it fills the existing object in place.
Follow-up: What should code do when it needs both the original and filled versions? Keep the default and assign the returned DataFrame to a new variable.
limit sets the maximum number of entries along the entire selected axis where missing values are filled. It defaults to None, meaning no such cap is applied.
Follow-up: What validation applies to limit? A supplied limit must be greater than zero.
pandas.DataFrame.isnapandas.DataFrame.dropnapandas.Series.fillnapandas.DataFrame.replace