xarray.Dataset.fillna#

Dataset.fillna(value)[source]#

Fill missing values in this object.

This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic, except the result is aligned to this object (join='left') instead of aligned to the intersection of index coordinates (join='inner').

Parameters

value (scalar, ndarray, DataArray, dict or Dataset) – Used to fill all matching missing values in this dataset’s data variables. Scalars, ndarrays or DataArrays arguments are used to fill all data with aligned coordinates (for DataArrays). Dictionaries or datasets match data variables and then align coordinates if necessary.

Returns

Dataset

Examples

>>> ds = xr.Dataset(
...     {
...         "A": ("x", [np.nan, 2, np.nan, 0]),
...         "B": ("x", [3, 4, np.nan, 1]),
...         "C": ("x", [np.nan, np.nan, np.nan, 5]),
...         "D": ("x", [np.nan, 3, np.nan, 4]),
...     },
...     coords={"x": [0, 1, 2, 3]},
... )
>>> ds
<xarray.Dataset>
Dimensions:  (x: 4)
Coordinates:
  * x        (x) int64 0 1 2 3
Data variables:
    A        (x) float64 nan 2.0 nan 0.0
    B        (x) float64 3.0 4.0 nan 1.0
    C        (x) float64 nan nan nan 5.0
    D        (x) float64 nan 3.0 nan 4.0

Replace all NaN values with 0s.

>>> ds.fillna(0)
<xarray.Dataset>
Dimensions:  (x: 4)
Coordinates:
  * x        (x) int64 0 1 2 3
Data variables:
    A        (x) float64 0.0 2.0 0.0 0.0
    B        (x) float64 3.0 4.0 0.0 1.0
    C        (x) float64 0.0 0.0 0.0 5.0
    D        (x) float64 0.0 3.0 0.0 4.0

Replace all NaN elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.

>>> values = {"A": 0, "B": 1, "C": 2, "D": 3}
>>> ds.fillna(value=values)
<xarray.Dataset>
Dimensions:  (x: 4)
Coordinates:
  * x        (x) int64 0 1 2 3
Data variables:
    A        (x) float64 0.0 2.0 0.0 0.0
    B        (x) float64 3.0 4.0 1.0 1.0
    C        (x) float64 2.0 2.0 2.0 5.0
    D        (x) float64 3.0 3.0 3.0 4.0